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"}
What is JSON? JSON stands for JavaScript Object Notation. JSON is a lightweight format for storing and transporting data. The JSON format consists of keys and values. In Swift, think of this format as a dictionary where each key must be unique and the values can be strings, numbers, bools, or null (nothing).
Sometimes JSON keys are named in a rather verbose manner or against the naming conventions of Swift. Thus, you commonly do not want to name your Swift object properties the same way as the JSON data. This is where you can specify a CodingKeys mapping. The CodingKey mapping maps the JSON names to the correct property names.
In Swift, Codable is a combination of Encodable and Decodable. Encodable means an object is convertible from Swift to JSON (or to another external representation). Decodable means an object is convertible from JSON (or other external representation) to Swift. Practically every iOS app handles JSON data in one way or another.
JSON is one of the most common data formats for transferring data between servers and devices. This will be a two part series. The first part will cover what JSON is and the basic handling in Swift while the second part will be focused on retrieving JSON from the web via URLSession and Alamofire.
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With