0

I am having hard time parsing following JSON array.

// JSON Array
[      
  {
    "ShaId": "adf56a4d",
    "Regions": [
      {
        "Name": "us-east-1a"
      }
    ]
  }
 .... more such
]     

Link to Go Playground :- https://play.golang.org/p/D4VrX3uoE8

Where am I making mistake?

Dhanu Gurung
  • 8,480
  • 10
  • 47
  • 60

1 Answers1

2

This is your original JSON input:

content := `{"ShaId": "adf56a4d", "Regions": [{"Name": "us-east-1a"}]}`

It is not an array, change it to:

content := `[{"ShaId": "adf56a4d", "Regions": [{"Name": "us-east-1a"}]}]`

With this, the result:

Results: []main.ShaInfo{main.ShaInfo{ShaId:"adf56a4d",
                Regions:main.Region{struct { Name string }{Name:"us-east-1a"}}}}

Note:

If you input is not an array, then don't try to parse an array (slice) out of it, just one ShaInfo. This also works if you don't/can't modify the input:

var data ShaInfo
content := `{"ShaId": "adf56a4d", "Regions": [{"Name": "us-east-1a"}]}`
json.Unmarshal([]byte(content), &data)

Output:

Results: main.ShaInfo{ShaId:"adf56a4d",
              Regions:main.Region{struct { Name string }{Name:"us-east-1a"}}}
icza
  • 389,944
  • 63
  • 907
  • 827
  • Will this work if I fetch the content reading any json file with above json? – Dhanu Gurung Mar 20 '15 at 11:06
  • @ram It doesn't matter where the JSON is coming from. But if your input JSON is not an array, then don't try to parse an array (slice) out of it, just one `ShaInfo`. – icza Mar 20 '15 at 11:07
  • Either this, or change the definition of `data` to `ShaInfo` rather than `[]ShaInfo`. – Phylogenesis Mar 20 '15 at 11:07