-1

I have read Unmarshaling nested JSON objects but I am still unsure how to handle the json:

{
   "input":{
      "lat":1234,
      "lon":1234
   },
   "stuff":[
      {
         "soc":"510950802051011",
         "bbox":[
            -76.743917,
            37.298812,
            -76.741184,
            37.300357
         ],
         "ccn":"51095",
         "name":"James",
         "age":"51",
         "gf":"Mary",
         "state":"NYC",
         "pea":"PEA033",
         "rea":"REA002",
         "rpc":"RPC002",
         "vpc":"VPC002"
      }
   ]
}

I would like to only access stuff.ccn, stuff.name

    package main
    import (
        "encoding/json"
        "fmt"   
    )

     func main() {

        jStr := `{
   "input":{
      "lat":1234,
      "lon":1234
   },
   "stuff":[
      {
         "soc":"510950802051011",
         "bbox":[
            -76.743917,
            37.298812,
            -76.741184,
            37.300357
         ],
         "ccn":"51095",
         "name":"James",
         "age":"51",
         "gf":"Mary",
         "state":"NYC",
         "pea":"PEA033",
         "rea":"REA002",
         "rpc":"RPC002",
         "vpc":"VPC002"
      }
   ]
}`


        type Inner struct {
            Key2 []string `json:"ccn"`
            Key3 []string `json:"name"`
        }
        type Outer struct {
            Key Inner `json:"stuff"`
        }
        var cont Outer
        json.Unmarshal([]byte(jStr), &cont)        
        fmt.Printf("%+v\n", cont)
    }

I think the issue I am having is with the array.

Shudipta Sharma
  • 5,178
  • 3
  • 19
  • 33
Brian
  • 848
  • 10
  • 32

2 Answers2

1

Your structs needs to follow what you have in JSON. In provided jStr where top level object maps to Outer you seem to have key stuff which is an array of Inner objects. You need to modify your types to reflect that like this:

    type Inner struct {
        Key2 string `json:"ccn"`
        Key3 string `json:"name"`
    }
    type Outer struct {
        Key []Inner `json:"stuff"`
    }

This basically says when stuff found take it as array and unmarshall each item as Inner.

blami
  • 6,588
  • 2
  • 23
  • 31
0

You can use json-to-go-struct one to get the go struct for your json.

Or simply use var cont map[string]interface{}

Shudipta Sharma
  • 5,178
  • 3
  • 19
  • 33