1

I am trying to parse JSON data from a weather API and get result JSON data printed to the console but I am having trouble accessing the data inside the multiple objects.

Im not sure if I should be doing structs for wind,atmosphere, condition or for speed, humidity, text, and temp

JSON Data:

    {
   "location":{
      "woeid": 2502265,
      "city":"Sunnyvale",
      "region":" CA",
      "country":"United States",
      "lat":37.371609,
      "long":-122.038254,
      "timezone_id":"America/Los_Angeles"
   },
   "current_observation":{
      "wind":{
         "chill":59,
         "direction":165,
         "speed":8.7
      },
      "atmosphere":{
         "humidity":76,
         "visibility":10,
         "pressure":29.68
      },
      "astronomy":{
         "sunrise":"7:23 am",
         "sunset":"5:7 pm"
      },
      "condition":{
         "text":"Scattered Showers",
         "code":39,
         "temperature":60
      },
      "pubDate":1546992000
   },
   "forecasts":[
      {
         "day":"Tue",
         "date":1546934400,
         "low":52,
         "high":61,
         "text":"Rain",
         "code":12
      },
      {
         "day":"Wed",
         "date":1547020800,
         "low":51,
         "high":62,
         "text":"Scattered Showers",
         "code":39
      },
      {
         "day":"Thu",
         "date":1547107200,
         "low":46,
         "high":60,
         "text":"Mostly Cloudy",
         "code":28
      },
      {
         "day":"Fri",
         "date":1547193600,
         "low":48,
         "high":61,
         "text":"Showers",
         "code":11
      },
      {
         "day":"Sat",
         "date":1547280000,
         "low":47,
         "high":62,
         "text":"Rain",
         "code":12
      },
      {
         "day":"Sun",
         "date":1547366400,
         "low":48,
         "high":58,
         "text":"Rain",
         "code":12
      },
      {
         "day":"Mon",
         "date":1547452800,
         "low":47,
         "high":58,
         "text":"Rain",
         "code":12
      },
      {
         "day":"Tue",
         "date":1547539200,
         "low":46,
         "high":59,
         "text":"Scattered Showers",
         "code":39
      },
      {
         "day":"Wed",
         "date":1547625600,
         "low":49,
         "high":56,
         "text":"Rain",
         "code":12
      },
      {
         "day":"Thu",
         "date":1547712000,
         "low":49,
         "high":59,
         "text":"Scattered Showers",
         "code":39
      }
   ]
}

class ForecastClass : Codable {
    var windSpeed : Int
    var humidity : Int
    var temperature : Int
    var text : String

        init(_ windSpeed: Int, _ humidity: Int, _ temperature: Int, _ text: String) {
            self.windSpeed = windSpeed
            self.humidity = humidity
            self.temperature = temperature
            self.text = text
        }
    }

//----------------------------\

struct Forecast : Codable {
    let windSpeed : Int
    let humidity : Int
    let temperature : Int
    let text : String
}
struct WeatherStruct : Codable{
    let weather : [Forecast]
}

Get weather function with API

func getWeather() {
        YahooWeatherAPI.shared.weather(lat: "37.372", lon: "-122.038", failure: { (error) in
            print(error.localizedDescription)
            print("Error pulling weather data")
        }, success: { (response) in
            let data = response.data
            let forecastInfo = try? JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String:Any]
            print(forecastInfo!)
        }, responseFormat: .json, unit: .imperial)
    }
4
  • Your sample JSON is invalid. Could you check it. Also, your question is not clear. Could you elaborate? Commented Sep 6, 2019 at 17:54
  • Please show real JSON data, not some debugger/print output. That said, pasting JSON into app.quicktype.io gives a very reasonable first version of the structs and parsing code you need. Commented Sep 6, 2019 at 17:54
  • This is not JSON, this is the forecastInfo dump. Yes, rather than JSONSerialization use structs and Codable. And you cannot mix scopes, for example humidity and temperature are in different scopes and windSpeed doesn't exist. Commented Sep 6, 2019 at 17:55
  • I just updated the sample JSON. Basically I am trying to populate the struct with the JSON data but I am not sure the best way/ how to access the different elements inside the objects. Commented Sep 6, 2019 at 18:05

1 Answer 1

1
struct Weather: Codable {
    let location: Location
    let currentObservation: CurrentObservation
    let forecasts: [Forecast]

    enum CodingKeys: String, CodingKey {
        case location
        case currentObservation = "current_observation"
        case forecasts
    }
}

struct CurrentObservation: Codable {
    let wind: Wind
    let atmosphere: Atmosphere
    let astronomy: Astronomy
    let condition: Condition
    let pubDate: Int
}

struct Astronomy: Codable {
    let sunrise, sunset: String
}

struct Atmosphere: Codable {
    let humidity, visibility: Int
    let pressure: Double
}

struct Condition: Codable {
    let text: String
    let code, temperature: Int
}

struct Wind: Codable {
    let chill, direction: Int
    let speed: Double
}

// MARK: - Forecast
struct Forecast: Codable {
    let day: String
    let date, low, high: Int
    let text: String
    let code: Int
}

struct Location: Codable {
    let woeid: Int
    let city, region, country: String
    let lat, long: Double
    let timezoneID: String

    enum CodingKeys: String, CodingKey {
        case woeid, city, region, country, lat, long
        case timezoneID = "timezone_id"
    }
}


do {
  let weather = try JSONDecoder().decode(Weather.self, from: data)
} catch {
  print(error)
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.