I have a struct like this:
type Result struct {
Data MyStruct `json:\"data,omitempty\"`
Status string `json:\"status,omitempty\"`
R
Data
is an initialized struct, so it isn't considered empty because encoding/json
only looks at the immediate value, not the fields inside the struct.
Unfortunately returning nil
from json.Marhsler
currently doesn't work:
func (_ MyStruct) MarshalJSON() ([]byte, error) {
if empty {
return nil, nil // unexpected end of JSON input
}
// ...
}
You could give Result
a marshaler as well, but it's not worth the effort.
The only option, as Matt suggests, is to make Data
a pointer and set the value to nil
.