Home >Backend Development >Golang >How to Omit Empty Nested Structs in Go's `json.Marshal`?
In complex JSON encoding scenarios, one may encounter situations where nested empty structs are also encoded when they should be omitted for space and efficiency purposes. For instance, consider the following code snippet:
type ColorGroup struct { ID int `json:",omitempty"` Name string Colors []string } type Total struct { A ColorGroup `json:",omitempty"` B string `json:",omitempty"` }
When json.Marshal is used on an instance of Total with an empty A field, it still appears in the output JSON:
group := Total{ A: ColorGroup{}, // An empty ColorGroup instance } json.Marshal(group) // Output: {"A":{"Name":"","Colors":null},"B":null}
The desired outcome is to omit the A field altogether:
{"B":null}
The key to addressing this issue lies in the use of pointers. If the A field in Total is declared as a pointer, it will be automatically set to nil when not explicitly assigned, resolving the problem of empty struct encoding:
type ColorGroup struct { ID int `json:",omitempty"` Name string Colors []string } type Total struct { A *ColorGroup `json:",omitempty"` // Using a pointer to ColorGroup B string `json:",omitempty"` }
With this modification, the json.Marshal output will now correctly omit the empty A field:
group := Total{ B: "abc", // Assigning a value to the B field } json.Marshal(group) // Output: {"B":"abc"}
The above is the detailed content of How to Omit Empty Nested Structs in Go's `json.Marshal`?. For more information, please follow other related articles on the PHP Chinese website!