Golang解析具有动态键的JSON

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

Golang parse a json with DYNAMIC key

问题

我有一个如下的 JSON 字符串:

j := `{"bvu62fu6dq": {
           "name": "john",
           "age": 23,
           "xyz": "weu33s"
           .....
           .....}
      }`

我想从上述 JSON 字符串中提取 nameage 的值。我看了 golang 网站上给出的这个例子 http://play.golang.org/p/YQgzP7KPp9

但我的问题是 JSON 中顶层的键是动态的。也就是说,bvu62fu6dq 是动态的。我已经创建了这样的结构体:

 type Info struct {
   UniqueID map[string]string
 }

但不确定如何提取 nameage。我的代码在这里 http://play.golang.org/p/Vbdkd3XIKc

英文:

I have a json string as follows:

j := `{"bvu62fu6dq": {
           "name": "john",
           "age": 23,
           "xyz": "weu33s"
           .....
           .....}
      }`

I want to extract the value of name and age from above json string. I looked at this example given at golang site http://play.golang.org/p/YQgzP7KPp9

But my problem is the key in the json on top level is dynamic. That means bvu62fu6dq is dynamic. I have created struct like this:

 type Info struct {
   UniqueID map[string]string
 }

But not sure how to extract name and age. My code is at http://play.golang.org/p/Vbdkd3XIKc

答案1

得分: 65

我相信你想要的是这样的:

type Person struct {
    Name string `json:"name"`
    Age  int    `json:"age"`
}

type Info map[string]Person

然后在解码后可以这样使用

fmt.Printf("%s: %d\n", info["bvu62fu6dq"].Name, info["bvu62fu6dq"].Age)

完整示例:http://play.golang.org/p/FyH-cDp3Na

英文:

I believe you want something like this:

type Person struct {
	Name string `json:"name"`
	Age  int    `json:"age"`
}

type Info map[string]Person

Then, after decoding this works:

fmt.Printf("%s: %d\n", info["bvu62fu6dq"].Name, info["bvu62fu6dq"].Age)

Full example: http://play.golang.org/p/FyH-cDp3Na

huangapple
  • 本文由 发表于 2013年8月24日 05:26:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/18412126.html
匿名

发表评论

匿名网友

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

确定