Golang parse a json with DYNAMIC key

2019-01-16 13:07发布

问题:

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:

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



标签: go