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!)