0

I tried to parse JSON data from a website api in Swift, but the api is a bit weird. What works is the following: [https://www.avanderlee.com/swift/json-parsing-decoding/][1]

This is a structure to parse/translate:

{
  "Meta Data": {
    "1. Information": "some info",
    "2. Symbol": "string symbol",
    "3. Last Refreshed": "2020-03-20 16:00:00",
    "4. Interval": "5min",
    "5. Output Size": "Compact",
    "6. Time Zone": "US/Eastern"
  },
  "Time Series (5min)": {
    "2020-03-20 16:00:00": {
      "1. keyABC": "138.2700",
      "2. keyCBA": "138.4900",
      "3. keyCAB": "136.6500",
      "4. keyACB": "136.7800",
      "5. keyBAC": "3392530"
    },
    "2020-03-20 15:55:00": {
      "1. keyABC": "137.7825",
      "2. keyCBA": "139.9112",
      "3. keyCAB": "137.0365",
      "4. keyACB": "138.2925",
      "5. keyBAC": "2463243"
    },
    "2020-03-20 15:50:00": {
      "1. keyABC": "139.0000",
      "2. keyCBA": "139.0150",
      "3. keyCAB": "137.7500",
      "4. keyACB": "137.7500",
      "5. keyBAC": "1051283"
    },
    ...
  }
}

Problem 1: There are random-keys as values that I need and don't know how to parse without just leaving deleting Problem 2: The JSON Libraries are not in an array instead in a new object. But the goal is to make a Swift array out of it

I wonder if there is an easy way to parse something like above with JSONDecode (and if there is one, what's the best?).

1 Answers1

1

app.quicktype.io provides a pretty good starting point for parsing this JSON:

struct JSONData: Codable {
    let metaData: MetaData
    let timeSeries5Min: [String: TimeSeries5Min]

    enum CodingKeys: String, CodingKey {
        case metaData = "Meta Data"
        case timeSeries5Min = "Time Series (5min)"
    }
}

struct MetaData: Codable {
    let the1Information, the2Symbol, the3LastRefreshed, the4Interval: String
    let the5OutputSize, the6TimeZone: String

    enum CodingKeys: String, CodingKey {
        case the1Information = "1. Information"
        case the2Symbol = "2. Symbol"
        case the3LastRefreshed = "3. Last Refreshed"
        case the4Interval = "4. Interval"
        case the5OutputSize = "5. Output Size"
        case the6TimeZone = "6. Time Zone"
    }
}

struct TimeSeries5Min: Codable {
    let the1KeyABC, the2KeyCBA, the3KeyCAB, the4KeyACB: String
    let the5KeyBAC: String

    enum CodingKeys: String, CodingKey {
        case the1KeyABC = "1. keyABC"
        case the2KeyCBA = "2. keyCBA"
        case the3KeyCAB = "3. keyCAB"
        case the4KeyACB = "4. keyACB"
        case the5KeyBAC = "5. keyBAC"
    }
}

Given that it should be fairly easy to extract whatever data you need into an array.

Gereon
  • 17,258
  • 4
  • 42
  • 73