43

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

0

1 Answer 1

68

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

Sign up to request clarification or add additional context in comments.

4 Comments

As I said, my key is dynamic and It wont be always bvu62fu6dq therefore I cannot use info["bvu62fu6dq"].Name
Sure, and info is a normal map. You can iterate over all keys or access any specific key, as usual for maps
@JVK How to do this if there are other keys parallel to bvu62fu6dq. e.g {"bvu62fu6dq": { "name": "john", "age": 23, }, "city": "NJ" }`
Please create map like this: data := map[string]Person{} full example: https://go.dev/play/p/gwdnB2kCd6-

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.