Here is my code:
func dump(w io.Writer, val interface{}) error {
je := json.NewEncoder(w)
return je.Encode(val)
}
type example struct {
Name string
Func func()
}
func main() {
a := example{
Name: "Gopher",
Func: func() {},
}
err := dump(os.Stdout, a)
if err != nil {
panic(err)
}
}
The program will panic with json: unsupported type: func()
My question is, how can I encode ANYTHING into json, ignoring those the encode cannot handle. For example, the above data structure, I want the output to be: {"Name": "Gopher"}
IMPORTANT: for the dump funtion, its value is an interface{}
, i.e. don't know what kind of data it will receive, so tricks like json:"-"
is not what I want.
If in case that the data passed to dump() is not marshal-able, e.g. dump(func(){})
, it is perfectly acceptable to just return empty string.
Is this what you are looking for: playground
You can use field tags to give json instructions on how to handle your struct. See also encoding/json for more info on the options you have.
-- edit --
It does not matter that val is of type interface{}
. json.Marshal()
will reflect on it anyway and find out what type it is. It is the programmers job to set the correct json
tags on all structs he/she wants to dump
.
You can also write a custom MarshalJSON function to do marshalling of every type however you like: custom marshalling playground
If you don't like the way golang handles json marshalling you could always write your own marshalling function doing all the reflection youself.
You can use json.RawMessage. It can be used to delay JSON decoding or precompute a JSON encoding.