Escaping a double quote within multiline string literal that contains double quotes already

Consider the following Swift code that contains a JSON-formatted string where the key and value are both strings:


let data = """
    {
        "height": "2'8\""
    }
    """.data(using: .utf8)!
let decoder = JSONDecoder()
do {
    let traits = try decoder.decode([String:String].self, from: data)
    print("traits = \(traits)")
}
catch let error {
    print("error decoding: \(error)")
}


What do I do when the string value (in this case, 2'8") needs to contain one double-quote? I tried doing it in the way shown above, but it results in, "error decoding: Error Domain=NSCocoaErrorDomain Code=3840 "Badly formed object around character 26." UserInfo={NSDebugDescription=Badly formed object around character 26.}"


If I try to leave out the backslash, I get the exact same error. If I leave out quotes entirely around the value, I get the same error, but in a different location (character 22 instead of character 26).


How do I escape the double quote within the string value, so that it can be decoded?

Accepted Reply

You need to escape the escaping character.


let data = """
    {
        "height": "2'8\\""
    }
    """.data(using: .utf8)!

Replies

You need to escape the escaping character.


let data = """
    {
        "height": "2'8\\""
    }
    """.data(using: .utf8)!