如何在嵌套结构中设置可选的 JSON?

huangapple go评论82阅读模式
英文:

How to set optional json in nest struct

问题

我尝试在嵌套结构中设置一个可选的 JSON 配置,当我需要这个 JSON 时,它会出现,否则它将不存在。

type Test struct {
  Data NestTest `json:"data"`
}

type NestTest struct {
  NestData1 string `json:"data1"`
  NestData2 string `json:"data2,omitempty"`
}

test := Test{
  Data: NestTest{
    NestData1: "something",
  },
}

b, err := json.Marshal(test)
fmt.Sprintf("the test struct json string is: %s", string(b))

输出:
{"data":{"data1":"something","data2":""}}

期望输出:
{"data":{"data1":"something"}}

英文:

I tried to set an optional json config in nest struct, when i need this json it will appear, otherwise it will not exist.

type Test struct {
  Data NestTest `json:"data"`
}

type NestTest struct {
  NestData1 string `json:"data1"`
  NestData2 string `json:"data2,omitempty"`
}

test := Test{
  Data: NestTest{
    NestData1: "something",
  },
}

b, err := json.Marshal(test)
fmt.Sprintf("the test struct json string is: %s", string(b))

output:
{"data":{"data1":"something","data2":""}}

expect:
{"data":{"data1":"something"}}

答案1

得分: 1

所有字段在解组时都是可选的(如果结构字段在JSON中没有关联的值,您不会收到错误)。在编组时,您可以使用omitempty来不输出一个字段,如果它包含其类型的零值:

https://pkg.go.dev/encoding/json#Marshal

var Test struct {
  Data string `json:"data,omitempty" validate:"option"`
}
英文:

All fields are optional when unmarshalling (you won't get an error if a struct field doesn't have an associated value in the JSON). When marshaling, you can use omitempty to not output a field if it contains its type's zero value:

https://pkg.go.dev/encoding/json#Marshal

var Test struct {
  Data string `json:"data,omitempty" validate:"option"`
}

huangapple
  • 本文由 发表于 2021年10月14日 21:54:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/69571988.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定