有没有办法在 golang 中查看我是否可以区分设置为 null 的 json 字段与解码为结构时不存在的 json 字段?因为两者都将结构中的值设置为 nil,但我需要知道该字段是否开始存在并查看是否有人将其设置为 null。
{
"somefield1":"somevalue1",
"somefield2":null
}
VS
{
"somefield1":"somevalue1",
}
当解码为结构时,两个 json 都将为 nil。 任何有用的资源将不胜感激!
最佳答案
在决定做某事之前,使用 json.RawMessage
来“延迟”解码过程以确定原始字节:
var data = []byte(`{
"somefield1":"somevalue1",
"somefield2": null
}`)
type Data struct {
SomeField1 string
SomeField2 json.RawMessage
}
func main() {
d := &Data{}
_ = json.Unmarshal(data, &d)
fmt.Println(d.SomeField1)
if len(d.SomeField2) > 0 {
if string(d.SomeField2) == "null" {
fmt.Println("somefield2 is there but null")
} else {
fmt.Println("somefield2 is there and not null")
// Do something with the data
}
} else {
fmt.Println("somefield2 doesn't exist")
}
}
看 Playground https://play.golang.org/p/Wganpf4sbO
关于JSON 字段设置为 null vs 字段不存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36601367/