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 ogg dd trandata 报错
  • ¥15 高缺失率数据如何选择填充方式
  • ¥50 potsgresql15备份问题
  • ¥15 Mac系统vs code使用phpstudy如何配置debug来调试php
  • ¥15 目前主流的音乐软件,像网易云音乐,QQ音乐他们的前端和后台部分是用的什么技术实现的?求解!
  • ¥60 pb数据库修改与连接
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错