golang json marshal: how to omit empty nested struct

后端 未结 2 1202
感情败类
感情败类 2020-12-14 14:15

go playground

As shown in the code above, one can use json:\",omitempty\" to omit certain fields in a struct to appear in json.

For example

相关标签:
2条回答
  • 2020-12-14 14:40

    Easy way

    type <name> struct {
    < varname > < vartype > \`json : -\`
    }
    

    Example :

    type Boy struct {
    name string \`json : -\`
    }
    

    this way on marshaling name will not get serialized.

    0 讨论(0)
  • 2020-12-14 15:04

    From the documentation:

    Struct values encode as JSON objects. Each exported struct field becomes a member of the object unless

    • the field's tag is "-", or
    • the field is empty and its tag specifies the "omitempty" option.

    The empty values are false, 0, any nil pointer or interface value, and any array, slice, map, or string of length zero.

    In your declaration of group, it's implicit that group.A will be the zero value of the ColorGroup struct type. And notice that zero-values-of-struct-types is not mentioned in that list of things that are considered "empty values".

    As you found, the workaround for your case is to use a pointer. This will work if you don't specify A in your declaration of group. If you specify it to be a pointer to a zero-struct, then it will show up again.

    playground link:

    package main
    
    import (
        "encoding/json"
        "fmt"
        "os"
    )
    
    func main() {
        type colorGroup struct {
            ID     int `json:",omitempty"`
            Name   string
            Colors []string
        }
        type total struct {
            A *colorGroup `json:",omitempty"`
            B string     `json:",omitempty"`
        }
    
        groupWithNilA := total{
            B: "abc",
        }
        b, err := json.Marshal(groupWithNilA)
        if err != nil {
            fmt.Println("error:", err)
        }
        os.Stderr.Write(b)
    
        println()
    
        groupWithPointerToZeroA := total{
            A: &colorGroup{},
            B: "abc",
        }
        b, err = json.Marshal(groupWithPointerToZeroA)
        if err != nil {
            fmt.Println("error:", err)
        }
        os.Stderr.Write(b)
    }
    
    0 讨论(0)
提交回复
热议问题