dseigqk7443 2015-10-31 02:03
浏览 232

golang json元帅:如何省略空的嵌套结构

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

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{},

}

In this case, B won't show up in json.Marshal(group)

However, if

group := Total{
       B:"abc",

}

A still shows up in json.Marshal(group)

{"A":{"Name":"","Colors":null},"B":"abc"}

Question is how do we get only

{"B":"abc"}

EDIT: After some googling, here is a suggestion use pointer, in other words, turn Total into

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

2条回答 默认 最新

  • dongmin3754 2015-10-31 03:03
    关注

    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)
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
  • ¥50 STM32单片机传感器读取错误
  • ¥15 (关键词-阻抗匹配,HFSS,RFID标签天线)
  • ¥15 机器人轨迹规划相关问题
  • ¥15 word样式右侧翻页键消失