使用未知字段名解析JSON

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

Unmarshal JSON with unknown field name

问题

我有一个JSON对象,类似于这样:

{
"randomstring": {
"everything": "here",
"is": "known"
}
}

基本上,randomstring 对象内的所有内容都是已知的,我可以对其建模,但是 randomstring 本身是随机的。我知道它将是什么,但每次都不同。基本上,我需要的所有数据都在 randomstring 对象中。我该如何解析这种JSON以获取数据?

英文:

I have a JSON object, something like this:

  1. {
  2. "randomstring": {
  3. "everything": "here",
  4. "is": "known"
  5. }
  6. }

Basically everything inside the randomstring object is known, I can model that, but the randomstring itself is random. I know what it's going to be, but it's different every time. Basically all the data I need is in the randomstring object. How could I parse this kind of JSON to get the data?

答案1

得分: 6

使用一个键类型为string,值类型为包含所需字段的结构体的映射,就像Playground上的这个示例和下面的代码一样:

  1. package main
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "log"
  6. )
  7. type Item struct{ X int }
  8. var x = []byte(`
  9. {"zbqnx": {"x": 3}}
  10. `)
  11. func main() {
  12. m := map[string]Item{}
  13. err := json.Unmarshal(x, &m)
  14. if err != nil {
  15. log.Fatal(err)
  16. }
  17. fmt.Println(m)
  18. }
英文:

Use a map where the key type is string and the value type is a struct with the fields you want, like in this example on the Playground and below:

  1. package main
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "log"
  6. )
  7. type Item struct{ X int }
  8. var x = []byte(`{
  9. "zbqnx": {"x": 3}
  10. }`)
  11. func main() {
  12. m := map[string]Item{}
  13. err := json.Unmarshal(x, &m)
  14. if err != nil {
  15. log.Fatal(err)
  16. }
  17. fmt.Println(m)
  18. }

huangapple
  • 本文由 发表于 2016年11月13日 09:07:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/40569482.html
匿名

发表评论

匿名网友

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

确定