使用Swift脚本打印有效的JSON

时间:2017-09-17 10:17:01

标签: json swift ubuntu

我试图在命令行中打印出包含JSON对象的变量的内容,如代码所示:

#! /usr/bin/swift
import Glibc
import Foundation

let albert_op = ProcessInfo.processInfo.environment["ALBERT_OP"]!


if albert_op == "METADATA" {
    let metadata = [
        ["iid": "org.albert.extension.external/v2.0",
        "name": "Tomboy",
        "version": "0.1",
        "author": "Will Timpson",
        "dependencies": ["tomboy", "python-pydbus"],
        "trigger": "tb "]
    ]
    print(metadata))
}


exit(0)

然而,打印出来:

[["trigger": "tb ", "name": "Tomboy", "iid": "org.albert.extension.external/v2.0", "dependencies": ["tomboy", "python-pydbus"], "version": "0.1", "author": "Will Timpson"]]

哪个无效,我期待的是:

{"version": "0.1", "author": "Will Timpson", "iid": "org.albert.extension.external/v2.0", "trigger": "tb ", "dependencies": ["tomboy", "python-pydbus"], "name": "Tomboy"}
  • 如何取得正确的结果?

5 个答案:

答案 0 :(得分:8)

两个问题:

  1. 你没有最终想要的结构。你有一个数组,其中包含一个项目,该项目是一个字典。根据您的预期输出,您似乎只想要一本字典。您可以通过删除额外的方括号来解决此问题。
  2. JSON是一种序列化格式。你没有"一个JSON对象。"您有要作为JSON序列化的数据。您可以使用JSONSerialization
  3. 执行此操作

    这是产生预期输出的工作代码:

    #! /usr/bin/swift
    
    import Foundation
    
    // Drop the extra brackets, and use a type annotation
    let metadata: [String: Any] = [
        "iid": "org.albert.extension.external/v2.0",
        "name": "Tomboy",
        "version": "0.1",
        "author": "Will Timpson",
        "dependencies": ["tomboy", "python-pydbus"],
        "trigger": "tb"
    ]
    
    // Serialize to JSON
    let jsonData = try JSONSerialization.data(withJSONObject: metadata)
    
    // Convert to a string and print
    if let JSONString = String(data: jsonData, encoding: String.Encoding.utf8) {
       print(JSONString)
    }
    
    // Output:
    // {"iid":"org.albert.extension.external\/v2.0","name":"Tomboy","version":"0.1","dependencies":["tomboy","python-pydbus"],"author":"Will Timpson","trigger":"tb"}
    

答案 1 :(得分:3)

Swift 4.2扩展
查找@smarx解决方案很多次以打印我的JSON字符串。 最终进行了扩展

extension Data
{
    func printJSON()
    {
        if let JSONString = String(data: self, encoding: String.Encoding.utf8)
        {
            print(JSONString)
        }
    }
}

答案 2 :(得分:1)

我建议使用do {} catch {()}块,并在序列化之前检查其是否为有效的JSON对象。

           do {

                    if let result = responseObj.result, JSONSerialization.isValidJSONObject(result) {

                        let jsonData = try JSONSerialization.data(withJSONObject: result)

                        // Convert to a string and print
                        if let JSONString = String(data: jsonData, encoding: String.Encoding.utf8) {
                            print(JSONString)
                        }
                    }
                } catch {
                    ()
                }

快乐的编码。

答案 3 :(得分:0)

迅速4:

例如,如果您想要快速弄脏一个衬纸,请检查您将要附加到http请求正文的序列化JSON数据,那么我将使用以下内容:

let json = NSString(data: myJsonObject, encoding: String.Encoding.utf8.rawValue)
print(json)

它打印为清晰的JSON,没有添加斜杠或其他任何东西!

答案 4 :(得分:0)

我想,我以一种非常简单的方式解决了这个问题。它显示了 xcode logcat中对象的格式正确的json。

let jsonString = object.toJSONString(prettyPrint: true)
print(jsonString as AnyObject)