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)
6
  • Could you please provide an example of JSON, and of the code you are using ? Thank you very much ! Commented Oct 25, 2022 at 12:03
  • Added example for json and decoding Commented Oct 25, 2022 at 12:09
  • The JSON is indeed invalid because inside the second level JSON the double quotes must be escaped. Commented Oct 25, 2022 at 12:44
  • @vadian I need to decode that json as a string Commented Oct 25, 2022 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\"}"` Commented Oct 25, 2022 at 13:07

1 Answer 1

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 .

Sign up to request clarification or add additional context in comments.

2 Comments

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.
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)!)).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.