Decode data as [String: String] while value can have json in it

292 Views Asked by At

So I have JSON, which has string keys and values which can be either strings or custom JSON, when I put json there (even if I put it in quotes) JSONDecoder throws an error "The given data was not valid JSON.", when there is a string everything is okay, is there maybe some decodable extension which can help with that? Coding Keys unfortunately not an option here. Example of json

"""
    {
        "someKey":"{
            "key1":"value1",
            "key2":"value2"
        }"
    }
"""

Decoding simply as

try JSONDecoder().decode([String: String].self, from: json)
1

There are 1 best solutions below

2
Pierre On

First, there are quotes to remove :

"""
    {
        "someKey":{
            "key1":"value1",
            "key2":"value2"
        }
    }
"""

Secondly, you will have to provide a more exact model :

import Foundation

var json = """
    {
        "someKey":{
            "key1":"value1",
            "key2":"value2"
        }
    }
"""

struct YourStructure: Codable
{
    var someKey: [String:String]
}

let result = try JSONDecoder().decode(YourStructure.self, from: json.data(using: .utf8)!)

JSONDecoder is not really designed for JSON with unknown model. If you would like to parse JSON for which you do not know the model before, you will have to use another library. I personnally use https://github.com/zoul/generic-json-swift .