Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Golang parse a json with DYNAMIC key [duplicate]

Tags:

go

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

like image 939
JVK Avatar asked Aug 23 '13 21:08

JVK


1 Answers

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

like image 73
Gustavo Niemeyer Avatar answered Sep 28 '22 23:09

Gustavo Niemeyer