Reputation: 1429
I have 2 structs:
type List struct {
ListID string `json:"listid"`
Name string `json:"name"`
Users []User `json:"users"`
}
type User struct {
Email string `json:"email"`
Name string `json:"name"`
}
I am calling an endpoint and successfully getting a response which has the structure below:
{
"Results":[
{"Email": "[email protected]", "Name": "test1" "State": "Active",…},
{"Email": "[email protected]", "Name": "test2" "State": "Active",…},
{"Email": "[email protected]", "Name": "test3", "State": "Active",…}
],
"SomeOtherStuff": "email"
}
I am trying to decode the JSON response to my struct like this:
err = json.NewDecoder(response.Body).Decode(&list.Users)
But there is no "Results" attribute in my struct to map to. How can I map only the Results key of the response to my array of User structs ?
Upvotes: 2
Views: 104
Reputation: 9623
To get your data there are at least two options:
Decode into map[string]interface{}
m := create(map[string]interface{})
err = json.NewDecoder(response.Body).Decode(&m)
Then use the m["results"] key to get at your users.
Or you could Decode into a container struct then assign list.Users = container.Results.
type Container struct {
Results []User `json:"Results"`
SomeOtherStuff string `json:"SomeOtherStuff"`
}
To get an idea of structs for arbitrary json look at json2go.
Upvotes: 2