Playing with Golang in my spare time. Trying to perform typical web task: get json from GET request and print its values.
type Weather struct {
name string
}
// some code
decoder := json.NewDecoder(res.Body)
for {
var weather Weather
if err := decoder.Decode(&weather); err == io.EOF {
break
} else if err != nil {
log.Fatal(err)
}
fmt.Println(weather.name)
}
JSON:
{"coord":{"lon":145.77,"lat":-16.92},"weather":[{"id":801,"main":"Clouds","description":"few clouds","icon":"02n"}],"base":"stations","main":{"temp":300.15,"pressure":1007,"humidity":74,"temp_min":300.15,"temp_max":300.15},"visibility":10000,"wind":{"speed":2.6,"deg":260},"clouds":{"all":20},"dt":1455633000,"sys":{"type":1,"id":8166,"message":0.0314,"country":"AU","sunrise":1455567124,"sunset":1455612583},"id":2172797,"name":"Cairns","cod":200}
As I understand, I need to declare a struct to get json values, but it prints nothing. What is my mistake?
And what if I need to operate json with unknown fields? Is there a way to construct map directly from json?