Home > Backend Development > Golang > How to Omit Empty Nested Structs in Go JSON Marshal?

How to Omit Empty Nested Structs in Go JSON Marshal?

Patricia Arquette
Release: 2024-12-16 02:41:14
Original
595 people have browsed it

How to Omit Empty Nested Structs in Go JSON Marshal?

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

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!

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