Reddy Reddy - 1 year ago 130
JSON Question

How to format a JSON String in Swift?

I have a JSON String that follows a format like

{ name: "John" }
and not
{ "name" : "John"}
and that is resulting in a nil whenever I try to access the name key because:

Error Domain=NSCocoaErrorDomain Code=3840 "No string key for value in object around character 1."

I am looking for a function that fixes/parses/formats this JSON file into something readable? How do sites like JSON Format do it?

Answer Source

Funny enough, { name: "John" } makes a valid JSON object in Javascript. So your problem now becomes finding a Javascript intepreter for Swift!

There's one built-in to recent versions of Mac OS X and iOS: WKWebView. It's a web rendering engine with a Javascript parser. Link your target with WebKit and try this:

import WebKit

class MyJSONParser {
    private static let webView = WKWebView()

    class func parse(jsonString: String, completionHandler: (AnyObject?, NSError?) -> Void) {
        self.webView.evaluateJavaScript(jsonString, completionHandler: completionHandler)


let str = "{ firstName: 'John', lastName: 'Smith' }"

// You must assign the JSON string to a variable or the Javascript
// will return void. Note that this runs asynchronously
MyJSONParser.parse("tmp = \(str)") { result, error in
    guard error == nil else {
    if let dict = result as? [String: String] {
    } else {
       print("Can't convert to Dictionary")
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download