Parser Json with Single Quote

Hi. I am having issues with json parsing. all my source data use double quote except for one.

here is the sample

do {
let json = "[['16772', 'Cebu', 'Philippines']]"

if let jsonArray = try JSONSerialization.jsonObject(with: Data(json.utf8), options: []) as? [[Any]] {
    print("Hello World")
}
} catch {
    print(error)
}

if the json string is

let json = "[[\"16772\", \"Cebu\", \"Philippines\"]]"

it works ok. but if it is single quote, then it gives out the error message

Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around line 1, column 2." UserInfo={NSDebugDescription=Invalid value around line 1, column 2., NSJSONSerializationErrorIndex=2}

What am i missing to enable parsing single quote normally? Thoughts?

Answered by Claude31 in 740979022

That's not a valid JSON format. So simply replace with correct chars:

do {
    let json = "[['16772', 'Cebu', 'Philippines']]".replacingOccurrences(of: "'", with: "\"")
    
    if let jsonArray = try JSONSerialization.jsonObject(with: Data(json.utf8), options: []) as? [[Any]] {
        print("Hello World")
    }
} catch {
    print(error)
}
Accepted Answer

That's not a valid JSON format. So simply replace with correct chars:

do {
    let json = "[['16772', 'Cebu', 'Philippines']]".replacingOccurrences(of: "'", with: "\"")
    
    if let jsonArray = try JSONSerialization.jsonObject(with: Data(json.utf8), options: []) as? [[Any]] {
        print("Hello World")
    }
} catch {
    print(error)
}

Before replacing the single to double quotes, check there are no double quotes inside the strings:

from: {'a': 'hello my "friend"!'}

to: {"a": "hello my "friend"!"} contains an error!

Is it possible to change the source of your json or run an script before generating it?

It looks like the json is coming from a call to a print function inside a python code (or similar language). If this is the case, try using the json package to dump the data in the correct format.

Best,

Parser Json with Single Quote
 
 
Q