I am attempting to print out in the command line the contents of a variable that holds a JSON object, like in the code:
#! /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)
However, that prints out:
[["trigger": "tb ", "name": "Tomboy", "iid": "org.albert.extension.external/v2.0", "dependencies": ["tomboy", "python-pydbus"], "version": "0.1", "author": "Will Timpson"]]
Which is not valid, I was expecting something like:
{"version": "0.1", "author": "Will Timpson", "iid": "org.albert.extension.external/v2.0", "trigger": "tb ", "dependencies": ["tomboy", "python-pydbus"], "name": "Tomboy"}
Two issues:
JSONSerialization
.Here's working code that produces the expected output:
#! /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"}