Home >Backend Development >Golang >How to Omit Empty Nested Structs in Go's `json.Marshal`?

How to Omit Empty Nested Structs in Go's `json.Marshal`?

DDD
DDDOriginal
2024-12-09 07:49:05998browse

How to Omit Empty Nested Structs in Go's `json.Marshal`?

golang json marshal: how to omit empty nested struct

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}

Solution: Utilizing Pointer Types

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!

Statement:
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