I am trying to parse a JSON API where I'm trying to extract the figures for the key value "data". As you can see these figures are nested inside two arrays where the second array doesn't have a key value to reference. How do I do this?
{
"dataset": {
"id": 9789340,
"name": "DCC share price (DCC), Currency GBX",
"description": "Stock Prices for Dcc Share Price (dcc), Currency Gbx from the London Stock Exchange.<br><br>Currency: GBX",
"start_date": "2006-03-16",
"end_date": "2017-11-22",
"column_names": [
"Date",
"Price",
"High",
"Low",
"Volume",
"Last Close",
"Change",
"Var%"
],
"data": [
[
"2017-11-22",
7060.0,
7185.0,
7045.0,
156444.0,
7060.0,
-95.0,
-1.33
],
[
"2017-11-21",
7155.0,
7210.0,
7130.0,
189002.0,
7155.0,
-30.0,
-0.42
]
]
}
}
So far I've done this.
struct Dataset: Decodable {
let name: String
let description: String
let column_names: [ColumnNames]
let data: [StockData]
}
struct ColumnNames: Decodable {
// What happens here??
}
struct StockData: Decodable {
// What happens here??
}
guard let url = URL(string : jsonUrlString) else { return }
URLSession.shared.dataTask(with: url) { (data, response, err) in
guard let jsonData = data else {
return
}
do {
let dataSet = try JSONDecoder().decode(Dataset.self, from: jsonData)
let dataArray = dataset.data
dump(dataArray)
for stockDataArray in dataArray {
for stockItems in stockDataArray
dump(stockItems)
}
}
}
As you can see I don't know how to decode "StockData" because JSON data is an array of arrays. If I have answer to this then hopefully I will be able to resolve "ColumnNames" should be parsed. It also isn't a dictionary with key values to parse.
dataare different (StringandDouble). So you have to decode it manually. Forcolumn_namesyou don't need a separate type. It's simply[String]. And without the date string the nesteddataarray would be simply[[Double]].column_names. It's a pity this won't work for data[[Any]]or[[String?]]JSONSerializationand merge fields and values.JSONSerializationis the best way to straighten this out. I was hoping to avoid this step because ultimately I plan to map this data to a persistent store withCore Data.