json - golang json编码(marshal): how to omit empty n

go playground

如上面的代码所示,可以使用 json:",omitempty" 省略结构中的某些字段以出现在 json 中。

例如

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

}

在这种情况下,B 不会出现在 json.Marshal(group)

但是,如果

group := Total{
       B:"abc",

}

A 仍然出现在 json.Marshal(group)

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

问题是我们如何得到唯一的

{"B":"abc"}

编辑: 经过一番谷歌搜索,这里有一个建议 use pointer ,也就是把Total变成

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

最佳答案

来自 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.

在您的 group 声明中,暗示 group.A 将是 ColorGroup 结构类型的零值。请注意,结构类型的零值在被视为“空值”的事物列表中未提及。

如您所见,针对您的情况的解决方法是使用指针。如果您没有在 group 的声明中指定 A,这将起作用。如果你指定它是一个指向零结构的指针,那么它会再次出现。

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

关于json - golang json编码(marshal): how to omit empty nested struct,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33447334/

相关文章:

javascript - 将 JSON 对象推送到 localStorage 中的数组

json - 有什么方法可以在运行时使用 webpack 加载资源?

javascript - JSON 无法解析的垃圾 : Why so serious?

python - json.loads 可以忽略尾随逗号吗?

ajax - 何时将 Ajax 与 Json 用于 Javascript 事件?

javascript - 如何从对象中删除所有 null 和空字符串值?

java - 如何测试 JSONObject 是否为空或不存在

javascript - 从 JSON 中选择不同的值

ruby-on-rails - JBuilder中未定义的局部变量或方法 `json'

python - IPython Notebook 中漂亮的 JSON 格式