go - golang json marshal: how to omit empty nested struct -
as shown in code above, 1 can use json:",omitempty"
omit fields in struct appear in json.
for example
type colorgroup struct { id int `json:",omitempty"` name string colors []string } type total struct { colorgroup`json:",omitempty"` b string`json:",omitempty"` } group := total{ a: colorgroup{}, }
in case, b
won't show in json.marshal(group)
however, if
group := total{ b:"abc", }
a
still shows in json.marshal(group)
{"a":{"name":"","colors":null},"b":"abc"}
question how only
{"b":"abc"}
edit: after googling, here suggestion use pointer, in other words, turn total
into
type total struct { *colorgroup`json:",omitempty"` b string`json:",omitempty"` }
from the documentation:
struct values encode json objects. each exported struct field becomes member of object unless
- the field's tag "-", or
- the field empty , tag specifies "omitempty" option.
the empty values false, 0, nil pointer or interface value, , array, slice, map, or string of length zero.
in declaration of group
, it's implicit group.a
0 value of colorgroup
struct type. , notice zero-values-of-struct-types not mentioned in list of things considered "empty values".
as found, workaround case use pointer. work if don't specify a
in declaration of group
. if specify pointer zero-struct, show again.
package main import ( "encoding/json" "fmt" "os" ) func main() { type colorgroup struct { id int `json:",omitempty"` name string colors []string } type total struct { *colorgroup `json:",omitempty"` b string `json:",omitempty"` } groupwithnila := total{ b: "abc", } b, err := json.marshal(groupwithnila) if err != nil { fmt.println("error:", err) } os.stderr.write(b) println() groupwithpointertozeroa := total{ a: &colorgroup{}, b: "abc", } b, err = json.marshal(groupwithpointertozeroa) if err != nil { fmt.println("error:", err) } os.stderr.write(b) }
Comments
Post a Comment