0

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?

1 Answer 1

1

Your 'name' field within your Weather struct is unexported. Field types must be exported for other packages to see them (and therefore, unmarshal/decode into them): https://tour.golang.org/basics/3

You can use struct tags to map Go field names to JSON keys as well:

type Weather struct {
    Name string `json:"name"`
}

... and for the future, you can use https://mholt.github.io/json-to-go/ to auto-generate Go structs from JSON.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.