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
Release: 2024-12-09 07:49:05
Original
1035 people have browsed it

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"`
}
Copy after login

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}
Copy after login

The desired outcome is to omit the A field altogether:

{"B":null}
Copy after login

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"`
}
Copy after login

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"}
Copy after login

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!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template