3

I am new to Go. I am working with a weather API. I have commented out the sections that cause the error. I have seen several other links that have a similar problem, however none of them seem to have the array in the middle of the JSON string. I'm sure there is a way to define the struct with a slice. I can't seem to get get the syntax to allow it. Here is where I'm stuck:

package main

import (
    "encoding/json"
    "fmt"
    "io/ioutil"
    "log"
    "net/http"
)

// WeatherData struct to collect data from the API call
type WeatherData struct {
    Wind Wind
    Sys  Sys
    // Weather Weather
    Name string `json:"name"`
}

////////////// ERROR when unmarshalling this struct /////////
// Weather provides basic weather info
// type Weather struct {
//  ID      int    `json:"id"`
//  Descrip string `json:"description"`
//  Icon    string `json:"icon"`
// }
/////////////////////////////////////////////////////////////

// Sys includes sunrise, sunset, country, etc.
type Sys struct {
    Country string `json:"country"`
}

// Wind struct to get specific wind characteristics
type Wind struct {
    Speed  float64 `json:"speed"`
    Degree float64 `json:"deg"`
    Gust   float64 `json:"gust"`
}

func main() {
    res, getErr := http.Get("http://api.openweathermap.org/data/2.5/weather?zip=REMOVED,us&appid=REMOVEDBUTWILLPOSTJSONData")
    if getErr != nil {
        log.Fatalln("http.Get error: ", getErr)
    }
    defer res.Body.Close()
    body, readErr := ioutil.ReadAll(res.Body)
    if readErr != nil {
        log.Fatalln("Read Error: ", readErr)
    }
//////////// UNABLE TO UNMARSHAL the array that passes through here ////
    var data WeatherData
    if err := json.Unmarshal(body, &data); err != nil {
        panic(err)
    }

    fmt.Println("Wind gusts: ", data.Wind.Gust)
    fmt.Println("Wind speed: ", data.Wind.Speed)
    fmt.Println("Wind degrees: ", data.Wind.Degree)

    fmt.Println("Country is: ", data.Sys.Country)
    fmt.Println("City is: ", data.Name)

///////////////// CAN'T ACCESS Description...or anything in Weather
// fmt.Println("Country is: ", data.Weather.Descrip) // cannot access due to this portion being inside an array

}



/////////////////THIS IS THE JSON DATA THAT IS AVAILABLE ///////////
{
  "coord": {
    "lon": -97.31,
    "lat": 32.94
  },
  "weather": [  // CAN'T ACCESS THIS CORRECTLY
    {
      "id": 800,
      "main": "Clear",
      "description": "clear sky",
      "icon": "01d"
    }
  ],
  "base": "stations",
  "main": {
    "temp": 306.46,
    "pressure": 1014,
    "humidity": 55,
    "temp_min": 306.15,
    "temp_max": 307.15
  },
  "visibility": 16093,
  "wind": {
    "speed": 5.1,
    "deg": 150,
    "gust": 7.2
  },
  "clouds": {
    "all": 1
  },
  "dt": 1499120100,
  "sys": {
    "type": 1,
    "id": 2597,
    "message": 0.0225,
    "country": "US",
    "sunrise": 1499081152,
    "sunset": 1499132486
  },
  "id": 0,
  "name": "Fort Worth",
  "cod": 200
}
3
  • Additional Links I have viewed with a very similar problem, but solutions don't quite fit my scenario: stackoverflow.com/questions/40626125/… Commented Jul 4, 2017 at 0:59
  • This link appears the closest, but I don't know how to create a custom unmarshaller as per their solution description... stackoverflow.com/questions/42377989/… Commented Jul 4, 2017 at 1:00
  • UPDATE: It still isn't working, but I have changed: type WeatherData struct { Wind Wind Sys Sys Weather []Weather ////////// this results in the values showing up, but I seem to lose the ability to identify the values based on their keys Name string json:"name"` }` Commented Jul 4, 2017 at 1:11

1 Answer 1

6

You have to define slice of Weather struct in WeatherData.

Uncomment Weather struct and update WeatherData struct to following.

// WeatherData struct to collect data from the API call
type WeatherData struct {
    Wind    Wind      `json:"wind"`
    Sys     Sys       `json:"sys"`
    Weather []Weather `json:"weather"`
    Name    string    `json:"name"`
}

Please have a look on example code: https://play.golang.org/p/4KFqRuxcx2

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

3 Comments

Thank you for trying to help, but I have been able to do that and get the chunk of array data, however I still can't call an individual key/value for something like data.Weather.Descrip it returns error that it is undefined. I've also tried adding the type []map[string]interface{} which works to give me all key/value pairs, but I still can't call them. You can see my change here: link
You need to access slice/array values via index, see here: link.
It works! Thank you so much. I had even gotten as far as accessing the whole thing by index 0, but didn't realize I could do dot notation on top of that. Thanks again!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.