Search code examples
swiftnsdictionaryquotesnsjsonserialization

Convert a string JSON to a dictionary in Swift when curly quotes are used


I have a string JSON, but it has fancy curly quotes in it which makes NSJSONSerialization fail.

let str = "{“title”:\"this is a “test” example\"}"

try! JSONSerialization.jsonObject(with: str.data(using: .utf8)!) // Error

The quotes around title are curly double quotes and apparently JSONSerialization can not handle it and fails. A naive approach would be to simple replace all instances of the curly quote with a non-curly one. The problem with that approach is that it will change the curly quotes around test which shouldn't be changed! The quotes around title are OK to be changed but the ones around test should not.

What can I do to get around this issue?


Solution

  • To fix this, you talk to whoever created the string, which does not contain JSON at the moment, and convince them to create a string that does contain JSON.

    For JSON the rule is: If your parser can't parse it, then it's broken and you don't touch it.

    The problem isn't that JSONSerialization cannot handle it. The problem is that JSONSerialization absolutely must not under any circumstances handle it. Because it's not JSON.