Reddy Reddy - 28 days ago 15
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

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)
    }
}

Usage:

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 {
        print(error)
        return
    }
    if let dict = result as? [String: String] {
        print(dict)
    } else {
       print("Can't convert to Dictionary")
    }
}