jsonswiftjsondecoder

How to decode a JSON with unknown keys at the top-level?


I would like to know how I can decode this JSON:

{
    "unknown_key1": {
        "info": "Info text",
        "text": "More text"
    },
    "unknown_key2": {
        "info": "Info text",
        "text": "More text"
    },
    ...
}

I have started writing something like this:

JSONDecode().decode(Test.self, from: data)

Test

struct Test: Decodable {
    let content: [String: Content]
}

struct Content: Decodable {
    let info: String
    let text: String
}

This doesn't work and I have no idea of what to do.

(I want to emphasize on the fact that I have set unknown_key1 and unknown_key2 as examples but these keys can be absolutely anything else.)


Solution

  • The JSON structure you posted is a Dictionary [String:Content].

    Decoding would look like:

    try JSONDecoder().decode([String:Content].self, from: data)
    

    there is no top level element.