我有一个 JSON 字符串,它遵循类似 { name: "John"}
而不是 { "name": "John"}
的格式,这导致了每当我尝试访问 name 键时返回 nil,因为:
Error Domain=NSCocoaErrorDomain Code=3840 “字符 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")
}
}
swift 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/