Home > Backend Development > Golang > How to Omit Empty Nested Structs in Go's JSON Marshaling?

How to Omit Empty Nested Structs in Go's JSON Marshaling?

Susan Sarandon
Release: 2024-12-13 22:21:16
Original
273 people have browsed it

How to Omit Empty Nested Structs in Go's JSON Marshaling?

Omitting Empty Nested Stucts in JSON Marshaling

Context:

JSON marshaling in Go enables converting structs into JSON objects. By default, all exported struct fields are included in the JSON output. However, empty fields can be omitted by specifying :",omitempty" as the field tag.

Problem:

If a nested struct is empty (i.e., has zero values for all its fields), it may still appear in the JSON output even though it has the :",omitempty" tag.

Solution:

To omit empty nested structs, it is necessary to use pointers to the structs. By doing so, the empty value of the nested struct will be considered a nil pointer.

Explanation:

From the Go documentation:

  • Struct values encode as JSON objects. Empty values include nil pointers.
  • The omitempty tag applies to empty values, including nil pointers.

Therefore, by using a pointer to the nested struct, we ensure that it is considered an empty value and thus omitted from the JSON output when the :",omitempty" tag is used.

Example:

type ColorGroup struct {
    ID     int `json:",omitempty"`
    Name   string
    Colors []string
}

type Total struct {
    A *ColorGroup `json:",omitempty"`
    B string     `json:",omitempty"`
}

// Empty nested struct (zero values)
group := Total{
    B: "abc",
}

// Marshal group without nested struct (only "B" field included)
b, err := json.Marshal(group)
if err != nil {
    fmt.Println("error:", err)
}
os.Stderr.Write(b)
Copy after login

The above is the detailed content of How to Omit Empty Nested Structs in Go's JSON Marshaling?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template