Hello I try to unmarshal the JSON response from api.nal.usda.gov/ndb into struct, but it always returns empty:
{ []}
Example JSON:
{
"list": {
"q": "butter",
"sr": "28",
"ds": "any",
"start": 0,
"end": 50,
"total": 4003,
"group": "",
"sort": "r",
"item": [
{
"offset": 0,
"group": "Branded Food Products Database",
"name": "BLUE BUNNY, PEANUT BUTTER PANIC, ICE CREAM, POWERFUL PEANUT BUTTER ICE CREAM CHARGED WITH PEANUT BUTTER AND FUDGE SAUCES AND OVERLOADED WITH PEANUT BUTTER CUPS, UPC: 070640034086",
"ndbno": "45011419",
"ds": "BL"
},
{
"offset": 1,
"group": "Branded Food Products Database",
"name": "BLUE BUNNY, ICE CREAM, PEANUT BUTTER PARTY, PEANUT BUTTER ICE CREAM, PEANUT BUTTER AND FUDGE SWIRLS, PEANUT BUTTER CUPS, UPC: 070640012411",
"ndbno": "45110466",
"ds": "BL"
}
]
}
}
I checked the JSON response with https://jsonformatter.curiousconcept.com/, and it´s fine. I hope you can tell me why, since I am quite new to Golang.
My Structs:
type List struct {
Q string `json:"q,omitempty"`
Sr string `json:"sr,omitempty"`
Ds string `json:"ds,omitempty"`
Start string `json:"start,omitempty"`
End string `json:"end,omitempty"`
Total string `json:"total,omitempty"`
Group string `json:"group,omitempty"`
Sort string `json:"sort,omitempty"`
Item []Item `json:"item,omitempty"`
}
type Item struct {
Offset string `json:"offset,omitempty"`
Group string `json:"group,omitempty"` //food group to which the food belongs
Name string `json:"name,omitempty"` //the food’s name
Ndbno string `json:"nbno,omitempty"` //the food’s NDB Number
Ds string `json:"ds,omitempty"` //Data source: BL=Branded Food Products or SR=Standard Release
}
Code:
func (sr *SearchRequest) fetch() {
url := "https://api.nal.usda.gov/ndb/search/?" +
"format=" + sr.format +
"&q=" + sr.q +
"&sort=" + sr.sort +
"&max=" + strconv.FormatInt(sr.max, 10) +
"&offset=" + strconv.FormatInt(sr.offset, 10) +
"&api_key=" + sr.c.ApiKey
r, err := http.Get(url)
if err != nil {
panic(err.Error())
}
defer r.Body.Close()
b, err := ioutil.ReadAll(r.Body)
if err != nil {
panic(err.Error())
}
l := new(List)
err = json.Unmarshal(b, &l)
if err != nil {
fmt.Println(err)
}
fmt.Println(l)
}