This question already has an answer here:
This is my first attempt at Go and I feel I'm missing something important here. Trying to decode a JSON message from a webservice but the output I'm getting is:
{response:{requests:[]}}
All I'm really interested in is the data within the request node. My for-loop obviously isn't getting called because the array is empty. I feel like my structs need to be declared exactly as they appear in the webservice?
Sample JSON:
{
"response": {
"requests": [
{
"request": {}
},
{
"request": {
"id": 589748,
"image_thumbnail": "",
"description": "Blah blah",
"status": "received",
"user": "test"
}
}
],
"count": "50",
"benchmark": 0.95516896247864,
"status": {},
"debug": {}
}
}
type Request struct {
id int `json:"id"`
description string `json:"description"`
user string `json:"user"`
}
type Requests struct {
request Request `json:"request"`
}
type Response struct {
requests []Requests `json:"requests"`
}
type RootObject struct {
response Response `json:"response"`
}
url := "<webservice>"
req, err := http.NewRequest("GET", url, nil)
req.Header.Set("Content-Type", "application/json")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
panic(err)
}
defer resp.Body.Close()
var r RootObject
decoder := json.NewDecoder(resp.Body)
decoder.Decode(&r)
fmt.Printf("%+v", r)
for _, req := range r.response.requests {
fmt.Printf("%d = %s
", req.request.id, req.request.user)
}
</div>