英文:
Golang parse a json with DYNAMIC key
问题
我有一个如下的 JSON 字符串:
j := `{"bvu62fu6dq": {
           "name": "john",
           "age": 23,
           "xyz": "weu33s"
           .....
           .....}
      }`
我想从上述 JSON 字符串中提取 name 和 age 的值。我看了 golang 网站上给出的这个例子 http://play.golang.org/p/YQgzP7KPp9
但我的问题是 JSON 中顶层的键是动态的。也就是说,bvu62fu6dq 是动态的。我已经创建了这样的结构体:
 type Info struct {
   UniqueID map[string]string
 }
但不确定如何提取 name 和 age。我的代码在这里 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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论