Go JSON Marshal: Omitting Empty Nested Structs
The json:",omitempty" tag in Go allows you to exclude fields that have empty values from JSON output. However, this behavior does not apply to zero-value structs.
To omit a nested struct if it has any empty fields, you can use a pointer instead of a non-pointer struct. This ensures that the struct is treated as empty if it has not been assigned a non-zero value.
For example, consider the following struct:
type ColorGroup struct { ID int `json:",omitempty"` Name string Colors []string } type Total struct { A *ColorGroup `json:",omitempty"` // Use pointer B string `json:",omitempty"` }
In this case, if group.A is not assigned a non-zero value, it will be treated as empty and omitted from JSON output. This is in contrast to using a non-pointer struct, which would still include the empty group.A in JSON output.
The following playground link demonstrates this behavior: https://play.golang.org/p/3i7rh4e3t3D
The above is the detailed content of How to Omit Empty Nested Structs in Go JSON Marshal?. For more information, please follow other related articles on the PHP Chinese website!