Why does Go error when trying to marshal this JSON? -
i'm trying rather simple example of trying decode json file structs using golang. however, when attempting error that
json: cannot unmarshal object go value of type []main.track
which don't understand. here's code in question, , json can found here.
package main import ( "encoding/json" "fmt" "net/http" "os" ) // tracks group of track types type tracks struct { tracks []track } // track represents singular track type track struct { name string url string artist artist } // artist represents single artist type artist struct { name string mbid string url string } func main() { url := "http://ws.audioscrobbler.com/2.0/?method=geo.gettoptracks&api_key=c1572082105bd40d247836b5c1819623&format=json&country=netherlands" response, err := http.get(url) if err != nil { fmt.printf("%s\n", err) os.exit(1) } defer response.body.close() var tracks tracks decodeerr := json.newdecoder(response.body).decode(&tracks) if decodeerr != nil { fmt.printf("%s\n", decodeerr) os.exit(1) } _, track := range tracks.tracks { fmt.printf("%s: %s\n", track.artist.name, track.name) } }
my initial thought maybe need categorize every single json value structs, didn't do, upon reading this article says:
there 2 answers this. easy option, when know data like, parse json struct you’ve defined. any field doesn’t fit in struct ignored. we’ll cover option first.
which leads me believe isn't that.
what doing wrong in scenario?
if @ json structure of response query you'll see single object tracks
property returned.
{ "tracks": { "track": [ {...} ] } }
if compare to given structs can see structure not align. given tracks
struct has field slice of track
s. if cast json represented following.
{ "tracks": [ { ... } ] }
this root of error. json decoder expecting tracks
field of root json object array. returned object contains tracks
property values json object contains track
property is array of tracks. update structures reflect schema follows.
// response object api type response struct { tracks tracks } // tracks group of track types type tracks struct { track []track } // track represents singular track type track struct { name string url string artist artist }
Comments
Post a Comment