Search code examples
jsonswiftjsondecoder

Swift: decode JSON with unknown keys?


I would like to decode a simple JSON file, the thing is that the top keys will all be different:

{
    "pikachu": {
        "name": "Pikachu",
        "number": 25
    },
    "bulbasaur": {
        "name": "Bulbasaur",
        "number": 1
    },
    "caterpie": {
        "name": "Caterpie",
        "number": 10
    }   
}

I have this model so far:

struct Pokemon: Decodable {
    //var key: ?
    var pokemonInfo: PokemonInfo
}

struct PokemonInfo: Decodable {
    var name: String
    var number: Int
}

But then I don't know how to set the Pokemon's key, as well as what to pass as a parameter for JSONDecoder.

let decodedResult = try JSONDecoder().decode([Pokemon].self, from: data)

typeMismatch(Swift.Array, Swift.DecodingError.Context(codingPath: [], debugDescription: "Expected to decode Array but found a dictionary instead.", underlyingError: nil))

What to do here?

Thank you for your help


Solution

  • There is no array and no key pokemonInfo in the JSON.

    As the keys are actually irrelevant the easiest solution is to decode [String:PokemonInfo] and map it to the values

    let decodedResult = Array(try JSONDecoder().decode([String:PokemonInfo].self, from: data).values)