Blog Posted June 4, 2017

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:

1
2
3
4
type MyStruct struct {
  Data   MyData `json:"data,omitempty"`
  Status string `json:"status,omitempty"`
}

And a str instance of MyStruct marshal'd to JSON:

1
2
3
4
5
6
7
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:

1
2
3
4
{
  "data": {},
  "status": "some-status"
}

How can we get the following JSON in such a data scenario, instead?

1
2
3
{
  "status": "some-status"
}

Solution: make MyData a pointer.

For example, declare MyStruct like so:

1
2
3
4
type MyStruct struct {
  Data   *MyData `json:"data,omitempty"`
  Status string `json:"status,omitempty"`
}

To yield JSON without a "data":

1
2
3
str := &MyStruct{
  Status: "some-status"
}

To yeild JSON with an empty "data": {}:

1
2
3
4
str := &MyStruct{
  Data: &MyData{},
  Status: "some-status"
}

To yield JSON with a non-empty "data":

1
2
3
4
5
6
str := &MyStruct{
  Data: &MyData{
    Foo: "bar"
  },
  Status: "some-status"
}