Serialize Empty Structs to JSON in Go
Problem: How can a Golang struct be serialized to JSON without including an empty object representing an empty struct within the parent struct?
For example, given a MyStruct
struct such as the following:
type MyStruct struct {
Data MyData `json:"data,omitempty"`
Status string `json:"status,omitempty"`
}
And a str
instance of MyStruct
marshal’d to JSON:
str := &MyStruct{
Status: "some-status"
}
j, _ := json.Marshal(str)
Println(string(j))
The yielded JSON contains an empty "data": {}
, which may be problematic, depending on usage:
{
"data": {},
"status": "some-status"
}
How can we get the following JSON in such a data scenario, instead?
{
"status": "some-status"
}
Solution: make MyData
a pointer.
For example, declare MyStruct
like so:
type MyStruct struct {
Data *MyData `json:"data,omitempty"`
Status string `json:"status,omitempty"`
}
To yield JSON without a "data"
:
str := &MyStruct{
Status: "some-status"
}
To yeild JSON with an empty "data": {}
:
str := &MyStruct{
Data: &MyData{},
Status: "some-status"
}
To yield JSON with a non-empty "data"
:
str := &MyStruct{
Data: &MyData{
Foo: "bar"
},
Status: "some-status"
}