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?

Accepted Reply

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)
}
  • Ok. that's what I did as workaround in the meantime. So there is really no other way for that except to change single to double quotes. I see. thank you.

  • Other option is to get the server to send valid JSON.

Add a Comment

Replies

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)
}
  • Ok. that's what I did as workaround in the meantime. So there is really no other way for that except to change single to double quotes. I see. thank you.

  • Other option is to get the server to send valid JSON.

Add a Comment

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,