在Go语言中,当解析JSON时,可以访问“额外”字段吗?

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

Can I access "extra" fields when unmarshalling json in Go?

问题

假设我有以下类型:

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

我想将这个 JSON 反序列化到这个类型中:

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

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

这样做是可以成功的。我至少想知道在处理过程中有哪些字段被跳过了。有没有什么好的方法可以访问这些信息?

playground 示例

英文:

Lets say I have this type:

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

and I want to unmarshal this json into it:

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

答案1

得分: 1

你可能已经知道,你可以将任何有效的 JSON 解析为 map[string]interface{}。在已经解析为 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)
    // 也可以使用反射从 Foo 中获取字段名作为字符串
    // 然后在这里嵌套另一个循环,将在 allFields 中但不在 Foo 上的任何键追加到切片中
}

请注意,这只是代码的翻译部分,没有回答你的问题。

英文:

As you're probably aware you can unmarshal any valid json into a 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. You could however, unmarshal into both types and then check the map for keys that don't correspond to fields on 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
}

huangapple
  • 本文由 发表于 2015年12月19日 02:30:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/34361860.html
匿名

发表评论

匿名网友

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

确定