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?

1 Answer 1

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"}}}
Sign up to request clarification or add additional context in comments.

3 Comments

Will this work if I fetch the content reading any json file with above json?
@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.
Either this, or change the definition of data to ShaInfo rather than []ShaInfo.

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.