json - 如何在 Swift 中格式化 JSON 字符串?

标签 json swift

我有一个 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/

相关文章:

java - Spring Boot Rest API - 输入文件+端点

Swift Parse MapView 不显示 CalloutAccessory 和 Segueing

arrays - swift数组的第n个元素的平均值

c# - 在 C# 中将列表对象转换为 json

ios - 拖动放置在 UIStackView 上的项目

swift - 来自事件包的字符串的 NSDate

ios - 如何从字符串中删除特殊字符\u{e2}

javascript - 创建正确的 json 字符串以存储在本地存储中

javascript - 从 JSON 文件中获取值并按键值排序

javascript - 如何为每个div添加一个JSON值?