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

As the docs say, “any nil pointer.” — make the struct a pointer. Pointers have obvious “empty” values: nil.

Fix – define the type with a struct pointer field:

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

Then a value like this:

result := Result{}

Will marshal as:

{}

Explanation: Notice the *MyStruct in our type definition. JSON serialization doesn’t care whether it is a pointer or not — that’s a runtime detail. So making struct fields into pointers only has implications for compiling and runtime).

Just note that if you do change the field type from MyStruct to *MyStruct, you will need pointers to struct values to populate it, like so:

Data: &MyStruct{ /* values */ }

Leave a Comment