How can I decode a JSON response with an unknown key in Swift?

You should take a look at Swift4 Codable protocol.

Create a structure for the currency dictionary values that conforms to Codable with the corresponding properties:

struct Currency: Codable {
    let fifteenM: Double
    let last: Double
    let buy: Double
    let sell: Double
    let symbol: String
    private enum CodingKeys: String, CodingKey {
        case fifteenM = "15m", last, buy, sell, symbol
    }
}

To decode your JSON data you need to use JSONDecoder passing the dictionary with custom values [String: Currency] as the type to be decoded:

let url = URL(string: "https://blockchain.info/ticker")!
URLSession.shared.dataTask(with: url) { data, response, error in
    guard let data = data else { return }
    do {
        let currencies = try JSONDecoder().decode([String: Currency].self, from: data)
        if let usd = currencies["USD"] {
            print("USD - 15m:", usd.fifteenM)
            print("USD - last:", usd.last)
            print("USD - buy:", usd.buy)
            print("USD - sell:", usd.sell)
            print("USD - symbol:", usd.symbol)
        }
    } catch { print(error) }

}.resume()

This will print

USD – 15m: 11694.03

USD – last: 11694.03

USD – buy: 11695.01

USD – sell: 11693.04

USD – symbol: $

Leave a Comment