-1

I am trying to parse json data which has nested objects.

Below is the sample data

{"Time Series (30min)": { "2018-10-16 16:00:00": { "1. open": "15.4700", "2. high": "15.5300", "3. low": "15.4500", "4. close": "15.5000", "5. volume": "1521981" }, "2018-10-16 15:30:00": { "1. open": "15.4600", "2. high": "15.4950", "3. low": "15.4400", "4. close": "15.4700", "5. volume": "397948" }}}

I know how to parse son arrays with decodable structs, but not sure how to do the same with this kind of data

Shehata Gamal
  • 98,760
  • 8
  • 65
  • 87
Sanyam koul
  • 87
  • 10
  • Do you mean you can't write structs for this json ??? – Shehata Gamal Oct 17 '18 at 12:41
  • I have created the structs for this and I am getting the data something like this Optional(EQUINOX.JSONValue.object(["2018-09-26 13:30:00": EQUINOX.JSONValue.object(["3. low": EQUINOX.JSONValue.string("16.5600"), "2. high": EQUINOX.JSONValue.string("16.6000"), "5. volume": EQUINOX.JSONValue.string("271397"), "1. open": EQUINOX.JSONValue.string("16.5700")])). what I don't understand is how to get the strings from the above data. I followed https://medium.com/grand-parade/parsing-fields-in-codable-structs-that-can-be-of-any-json-type-e0283d5edb to write the structs. – Sanyam koul Oct 17 '18 at 12:50

1 Answers1

1

You can use this

struct Root: Codable {

    let timeSeries: [String: InnerItem]

    enum CodingKeys: String, CodingKey {
        case timeSeries = "Time Series (30min)"
    }
}

struct InnerItem: Codable {

    let open,high,low,close,volume: String 

    enum CodingKeys: String, CodingKey {
        case open = "1. open"
        case high = "2. high"
        case low = "3. low"
        case close = "4. close"
        case volume = "5. volume"
    }
}

do {
   let res = try JSONDecoder().decode(Root.self,from:jsonData)
}
catch {
   print(error)
}
Shehata Gamal
  • 98,760
  • 8
  • 65
  • 87