0

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)
Andrii
  • 30
  • 3
  • Could you please provide an example of JSON, and of the code you are using ? Thank you very much ! – Pierre Oct 25 '22 at 12:03
  • Added example for json and decoding – Andrii Oct 25 '22 at 12:09
  • The JSON is indeed invalid because inside the *second level* JSON the double quotes must be escaped. – vadian Oct 25 '22 at 12:44
  • @vadian I need to decode that json as a string – Andrii Oct 25 '22 at 13:04
  • 1
    I got that, but the error *The given data was not valid JSON* means what it says. Valid JSON is "someKey":"{\"key1\":\"value1\",\ "key2\":\"value2\"}"` – vadian Oct 25 '22 at 13:07
  • As vadian notes, this isn't valid JSON, so you're going to need to either convert it to be valid JSON (by writing something that modifies the string), fix the producing code to generate valid JSON, or write your own string parser. – Rob Napier Oct 25 '22 at 13:37

1 Answers1

1

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 .

Pierre
  • 422
  • 2
  • 12
  • 3
    Isn't the whole point of the question the fact that the quotes are there and how to handle them? I think you should assume the json is from an external source so manually removing the quotes in an editor is hardly an option then. – Joakim Danielson Oct 25 '22 at 12:32
  • Well, I missed a bit context, but in this case, he would just have to declare `someKey` as string, then decode again the json inside as a `[String:String]` (`let result2 = try JSONDecoder().decode([String:String].self, from: result.someKey.data(using: .utf8)!)`). – Pierre Oct 25 '22 at 13:14