我有一个JSON字符串,它遵循类似于{ name: "John" }
而不是{ "name" : "John"}
的格式,因此每当我试图访问name键时都会导致nil,因为:Error Domain=NSCocoaErrorDomain Code=3840 "No string key for value in object around character 1."
我正在寻找一个函数,它可以将这个JSON文件修复/解析/格式化为可读的内容?像JSON Format这样的网站是如何做到的?
最佳答案
有趣的是,{ name: "John" }
在Javascript中生成了一个有效的JSON对象。所以现在你的问题是为Swift找到一个Javascript接口!
Mac OS X和iOS的最新版本有一个内置版本:WKWebView
。它是一个带有Javascript解析器的web呈现引擎。将目标链接到WebKit并尝试以下操作:
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 {
print(error)
return
}
if let dict = result as? [String: String] {
print(dict)
} else {
print("Can't convert to Dictionary")
}
}
斯威夫特3
import WebKit
class MyJSONParser {
private static let webView = WKWebView()
class func parse(jsonString: String, completionHandler: @escaping (Any?, Error?) -> 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(jsonString: "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")
}
}
关于json - 如何在Swift中格式化JSON字符串?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36825601/