Printing valid JSON with a Swift script
I would recommend using do {} catch { () } block, and before serialization do check if its a valid JSON object.
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 {
()
}
Happy coding.
Swift 4.2 Extension
Looked up @smarx solution a lot of times to print my JSON string.
Eventually ended up making an extension
extension Data
{
func printJSON()
{
if let JSONString = String(data: self, encoding: String.Encoding.utf8)
{
print(JSONString)
}
}
}
Two issues:
- You don't have the structure you ultimately want. You have an array with one item in it, and that item is a dictionary. Based on your expected output, you seem to just want a dictionary. You can fix this by dropping the extra square brackets.
- JSON is a serialization format. You don't have "a JSON object." You have data that you would like to serialize as JSON. You can do that with
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"}
Swift 4:
If you want a quick dirty one liner just for example, checking the serialised JSON Data you are about to attach to a http request body then I use the following:
let json = NSString(data: myJsonObject, encoding: String.Encoding.utf8.rawValue)
print(json)
It prints as clear JSON, no added slashes or anything!