JSON Encoding without null values / dynamic struct creation

73 views
Skip to first unread message

Gyu-Ho Lee

unread,
Feb 27, 2015, 2:29:42 AM2/27/15
to golan...@googlegroups.com
Hello,

I wonder what would be the best way to encode JSON with null values if I do not want to encode them in the JSON object. I am totally ok with many null values in encoded JSON. I just wonder if we can dynamically generate struct data type for each JSON object as we encode it, just for clearer output.

http://play.golang.org/p/fzeQnpdISo

type myData struct {
A string `json:"a_str"`
B string `json:"b_str"`
C string `json:"c_str"`
}
myMap := make(map[string][]myData)
data1 := myData{A: "hello", B: "gopher"}
data2 := myData{}
data3 := myData{A: "hey", B: "here", C: "golang"}
myMap["1"] = []myData{data1, data2, data3}
myMap["2"] = []myData{data2, data3}
myMap["3"] = []myData{data2}
buf := new(bytes.Buffer)
myMapInterface := make(map[string]interface{})
for k, v := range myMap {
myMapInterface[k] = interface{}(v)
}
err := json.NewEncoder(buf).Encode(myMapInterface)
if err != nil {
log.Fatal(err)
}
fmt.Println(buf.String())
// Is there anyway that I can exclude to encode empty elements in the struct?
// e.g. {"a_str":"","b_str":"A","c_str":""} -> {"b_str":"A"}


For example, when given {"a_str":"","b_str":"A","c_str":""}
is there anyway we can dynamically create a different struct like:

type _myData struct {
B string `json:"b_str"`
}

so that the encoded JSON does not have the null values in it


Thanks!

Klaus Post

unread,
Feb 27, 2015, 4:23:29 AM2/27/15
to golan...@googlegroups.com

Using omitempty?



/Klaus

Gyu-Ho Lee

unread,
Feb 27, 2015, 4:32:11 AM2/27/15
to golan...@googlegroups.com
This was exactly what I was looking for. Thanks!
Reply all
Reply to author
Forward
0 new messages