Saamer
Saamer

Reputation: 5099

Escaped Double Quote in Swift breaking JSONDecoder decode

If you open a play ground and paste this code, you'll notice that the decoded object is nil. The JSON object [{"transcript":"A person might say, \"Hello\"."}] passes any linter successfully but it seems like the default JSON decoder in Swift has an issue with the escaped double quotes (\") in the transcript. To make sure, in my playground when I remove the two escaped double quotes from the string, it works fine.

var testData2 = """
[{"transcript":"A person might say, \"Hello\"."}]
"""
struct TranscriptModel: Codable, Identifiable {
    let id = UUID()
    let transcript : String
}
typealias Transcripts = [TranscriptModel]
let decodedResponse1 = try? JSONDecoder().decode(Transcripts.self, from: Data(testData2.utf8))
print(decodedResponse1)

It seems like a bug in Swift's JSON decoder? Is there a work around so that I can show double quotes in my json string?

If used by itself within your code, swift recognizes the escaped double quote and works perfectly by showing the " symbol as you can see in the picture below Playground screenshot showing this behavior

This is causing a much bigger issue in my application, but I just broke down the error to where it's reproducible in an easy way

I am sharing an example of the same JSON string working in JavaScript too CodePen Example

Upvotes: -2

Views: 176

Answers (1)

xAlien95
xAlien95

Reputation: 406

In a JSON file, a string containing the " character must escape it as \". In Swift, however, a string containing the \ character must escape it as \\.

Your example works if the JSON string provides \\", where \\ is required by Swift and translates to \ and \" is required by the JSON syntax.

var testData2 = """
[{"transcript":"A person might say, \\"Hello\\"."}]
"""

You can alternatively avoid escaping \ by using a raw string literal as follows:

var testData2 = #"""
[{"transcript":"A person might say, \"Hello\"."}]
"""#

Upvotes: 1

Related Questions