0

I received JSON below from a client API but i am struggling to get nested JSON content. How can I parse it if the inner keys are dynamic?

const jsonStream = `
{
    "items": {
        "bvu62fu6dq": {
            "name": "john",
            "age": 23,
            "xyz": "weu33s"
        },
        "iaxdw23fq": {
            "name": "kelly",
            "age": 21,
            "xyz": "weu33s"
        }
    }
}`

This is what i have tried below by looping the map to extract the value of name and age from above JSON string; but it returns map with nil value as a result. goplaygound

type Person struct {
    Name string `json:"name"`
    Age  int    `json:"age"`
}
type Item struct {
    Contact struct {
        Info map[string]Person
    } `json:"items"`
}

func main() {
    dec := json.NewDecoder(strings.NewReader(jsonStream))
    for {
        var item Item
        if err := dec.Decode(&item); err == io.EOF {
            break
        } else if err != nil {
            log.Fatal(err)
        }
        fmt.Printf("%s\n", item.Contact.Info["bvu62fu6dq"].Name)
    }
}
2
  • Could you edit your question explaining the point of the unique keys? It is only mentioned in the title Commented Sep 27, 2015 at 7:19
  • It will be easier if you say that, and in what form you need to get. Commented Sep 27, 2015 at 8:19

1 Answer 1

6

Try this instead, looks like you just have your structure set up incorrectly:

http://play.golang.org/p/VRKbv-GVQB

You need to parse the entire json string, which is an object that contains a single element named items. items then contains a map of string -> Person objects.

If you only want to extract name and age from each person, you do it by grabbing data.Items["bvu62fu6dq"].Name.

If you want dynamic keys inside the Person, you'll need to do map[string]interface{} instead of Person in order to capture the dynamic keys again. It would look something like:

type Data struct {
    Items map[string]map[string]interface{} `json:"items"`
}
...
fmt.Printf("%v\n", data.Items["bvu62fu6dq"]["name"]
fmt.Printf("%v\n", data.Items["bvu62fu6dq"]["age"]
fmt.Printf("%v\n", data.Items["bvu62fu6dq"]["xyz"]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.