I'm calling a remote API and getting a JSON response back. I'm trying to convert the *http.Response into a struct that I defined. Everything i've tried so far has resulted in an empty struct. Here is my attempt with json.Unmarshal
type Summary struct {
Created string `json:"created"`
High float64 `json:"high"`
Low float64 `json:"low"`
}
func getSummary() {
url := "http://myurl"
resp, err := http.Get(url)
if err != nil {
log.Fatalln(err)
}
body, err2 := ioutil.ReadAll(resp.Body)
if err2 != nil {
panic(err.Error())
}
log.Printf("body = %v", string(body))
//outputs: {"success":true,"message":"","result":["High":0.43600000,"Low":0.43003737],"Created":"2017-06-25T03:06:46.83"}]}
var summary = new(Summary)
err3 := json.Unmarshal(body, &summary)
if err3 != nil {
fmt.Println("whoops:", err3)
//outputs: whoops: <nil>
}
log.Printf("s = %v", summary)
//outputs: s = &{{0 0 0 0 0 0 0 0 0 0}}
}
What am I doing wrong? The JSON tags in my struct match the json keys from the response exactly...
edit: here is the JSON returned from the API
{
"success": true,
"message": "''",
"result": [
{
"High": 0.0135,
"Low": 0.012,
"Created": "2014-02-13T00:00:00"
}
]
}
edit i changed the struct to this but still not working
type Summary struct {
Result struct {
Created string `json:"created"`
High float64 `json:"high"`
Low float64 `json:"low"`
}
}
whoopserror. Using%voutputs the exact sameerr3=<nil>if the previous if statement requires thateer3is not nil?bodyis not valid JSON. You have to remove the%!(EXTRA string=and the)in order to be able to usejson.Unmarshalon it.Summaryis not the same shape as the JSON data anyway. You need to make it match the shape of the whole JSON object (after removing the portions mentioned above) in order to be able to unmarshal it.