简体   繁体   English

在Go中解组json时,我可以访问“额外”字段吗?

[英]Can I access “extra” fields when unmarshalling json in Go?

Lets say I have this type: 可以说我有这种类型:

type Foo struct{
   Bar string `json:"bar"`
}

and I want to unmarshal this json into it: 我想把这个json解组成它:

in := []byte(`{"bar":"aaa", "baz":123}`)

foo := &Foo{}
json.Unmarshal(in,foo)

will succeed just fine. 会成功的。 I would like to at least know that there were fields that were skipped in the processing. 我想至少知道在处理过程中有些字段被跳过了。 Is there any good way to access that information? 有没有什么好方法可以访问这些信息?

playground snippet 游乐场片段

As you're probably aware you can unmarshal any valid json into a map[string]interface{} . 您可能已经知道,您可以将任何有效的json解组为map[string]interface{} Having unmarsahled into an instance of Foo already there is no meta data available where you could check fields that were excluded or anything like that. 已经没有mamaahled到Foo的实例,没有可用的元数据,您可以检查被排除的字段或类似的字段。 You could however, unmarshal into both types and then check the map for keys that don't correspond to fields on Foo . 但是,您可以解组两种类型,然后检查地图中是否与Foo上的字段不对应的键。

in := []byte(`{"bar":"aaa", "baz":123}`)

foo := &Foo{}
json.Unmarshal(in,foo)

allFields := &map[string]interface{}
json.Unmarshal(in, allFields)
for k, _ := range allFields {
    fmt.Println(k)
    // could also use reflect to get field names as string from Foo
    // the get the symmetric difference by nesting another loop here
    // and appending any key that is in allFields but not on Foo to a slice
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM