Home > Backend Development > Golang > How Do I Properly Handle Nested Empty Structs When Marshaling to JSON in Go?

How Do I Properly Handle Nested Empty Structs When Marshaling to JSON in Go?

Susan Sarandon
Release: 2024-12-18 06:41:10
Original
560 people have browsed it

How Do I Properly Handle Nested Empty Structs When Marshaling to JSON in Go?

Handling Nested Empty Structs in JSON Marshaling in Go

Introduction

When using the encoding/json package in Go for marshalling structs to JSON, the ",omitempty" tag can be used to exclude empty fields from the resulting JSON. However, this tag may not behave as expected for nested structs.

Question

Consider the following example:

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

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

group := Total{
    A: ColorGroup{},
}

json.Marshal(group)
Copy after login

In this scenario, the JSON output should only include the B field, since the A field is empty. However, the output still includes the A field with empty values ({"A": {"Name": "", "Colors": null}, "B": null}).

Answer

The documentation for json marshaling in Go states that struct fields are considered empty if they are:

  • Nil pointers
  • Zero values (e.g., false, 0)

In the provided example, group.A is an empty struct, not a nil pointer or a collection type (e.g., slice, map). Therefore, it's not treated as an empty value by the marshaler.

To achieve the desired behavior, one can use a pointer to the nested struct:

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

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

group := Total{
    B: "abc",
}

json.Marshal(group)
Copy after login

With this modification, the JSON output will include only the B field: {"B": "abc"}.

Note:

  • If a pointer to a non-zero struct is passed, it will be included in the JSON output, even if it's empty.
  • This solution can only be applied to nested structs. For non-nested empty structs, using the ",omitempty" tag without pointers will suffice.

The above is the detailed content of How Do I Properly Handle Nested Empty Structs When Marshaling to JSON in Go?. 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