0

I am currently trying to parse the JSON I get back from the IEX api. The problem I am running into is that the response is dynamic, depending on which stock names you request, the keys in the JSON response change. So when requesting the AAPL stock info, the returned JSON is:

{"AAPL":{"quote":{"symbol":"AAPL","companyName":"Apple Inc.","primaryExchange":"Nasdaq Global Select","sector":"Technology","calculationPrice":"close","open":158.53,"openTime":1546266600303,"close":157.74,"closeTime":1546290000568,"high":159.36,"low":156.48,"latestPrice":157.74,"latestSource":"Close"}}

And requesting multiple stocks in one request returns JSON that can be seen here: https://api.iextrading.com/1.0/stock/market/batch?symbols=AAPL,GOOGL,AAPL&types=quote,chart&range=1m

The decodable structs I am using are the following:

struct Symbol: Decodable {
let quote: Quote
let chart: [Chart]
}

struct Chart: Decodable {
let date: String
let open, high, low, close: Double
let volume, unadjustedVolume: Int
let change, changePercent, vwap: Double
let label: String
let changeOverTime: Double

}

struct Quote: Decodable {
let symbol, companyName, primaryExchange, sector: String
let calculationPrice: String
let open: Double
let openTime: Int
let close: Double
let closeTime: Int
let high, low, latestPrice: Double
let latestSource, latestTime: String
let latestUpdate, latestVolume: Int
let delayedPrice: Double
let delayedPriceTime: Int
let extendedPrice, extendedChange, extendedChangePercent: Double
let extendedPriceTime: Int
let previousClose, change, changePercent: Double
let avgTotalVolume: Int
let marketCap: Int
let peRatio, week52High, week52Low, ytdChange: Double

}

Using

let parsedData = try JSONDecoder().decode([String:Symbol].self, from: data!)

works but when trying to access only the Symbol objects I get only nil values so I have no idea whats going on there. Im looking for a solution like with JSON.net in C# which enables you to do

let parsedData = try JSONDecoder().decode(dictionary<String,Symbol>, from: data!)
Thijs van der Heijden
  • 1,147
  • 1
  • 10
  • 25
  • Please note that you have not explained what is "dynamic" about your JSON; you showed just one stock result and stopped, so how do we know how a different stock would be different? If keys may or not be present, use Optional struct properties. If key names themselves can change, as your "dynamic" title implies, see the linked duplicate. – matt Jan 01 '19 at 20:37
  • What error do you get when you `catch` the error? At first glance I see that there is no `chart` key and a few keys are missing in the `quote` dictionary. – vadian Jan 01 '19 at 20:37
  • If you're not sure whether or not a key will be in the response, you should make it optional (ex: `let myValue: Int?` instead of `let myValue: Int`) – Adrian Jan 02 '19 at 03:02

0 Answers0