Matt Matt - 1 year ago 73
JSON Question

How to not marshal an empty struct into JSON with Go?

I have a struct like this:

type Result struct {
Data MyStruct `json:"data,omitempty"`
Status string `json:"status,omitempty"`
Reason string `json:"reason,omitempty"`

But even if the instance of MyStruct is entirely empty (meaning, all values are default), it's being serialized as:


I know that the encoding/json docs specify that "empty" fields are:

false, 0, any nil pointer or interface value, and any array,
slice, map, or string of length zero

but with no consideration for a struct with all empty/default values. All of its fields are also tagged with
, but this has no effect.

How can I get the JSON package to not marshal my field that is an empty struct?

Answer Source

Oh! Easy fix: "any nil pointer." -- make the struct a pointer.


type Result struct {
    Data       *MyStruct `json:"data,omitempty"`
    Status     string    `json:"status,omitempty"`
    Reason     string    `json:"reason,omitempty"`

Notice the *MyStruct -- when I create a MyStruct now, I simply do so by reference:

myStruct := &MyStruct{ /* values */ }

And now the "empty" MyStruct is no longer marshaled into JSON as desired.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download