Reputation: 1607
With an http GET request I'm importing a JSON response into a string. I want to add the JSON string into a struct array with json.Unmarshal. This works only when I remove at the beginning the fields data & categoryGroups. They are not part of my strucs. So by removing {"data":{"categoryGroups": at the beginning and }} at the end.
This can be done with a strings.Replace, but I'm wondering if there is a neater solution?
{"data":{"categoryGroups":[{"name":"...."}]}]}}
Upvotes: 1
Views: 437
Reputation: 751
Based on suggestions from comments, I reproduced your scenario as follows:
package main
import (
"encoding/json"
"fmt"
)
var data = []byte(`{"data":{"categoryGroups":[{"name":"group1"}]}}`)
type CategoryGroup struct {
Name string `json:"name"`
}
func main() {
var v struct {
Data struct {
CategoryGroups []CategoryGroup `json:"categoryGroups"`
} `json:"data"`
}
if err := json.Unmarshal(data, &v); err != nil {
panic(err)
}
cgs := v.Data.CategoryGroups
fmt.Println(cgs)
}
Output:
[{group1}]
Upvotes: 1