Created
May 12, 2020 08:29
-
-
Save JanGorman/b4c150182aa2292c98c965dd2c07d87b to your computer and use it in GitHub Desktop.
JSON Swift String Interpolation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extension String.StringInterpolation { | |
mutating func appendInterpolation(json JSONData: Data) { | |
guard let JSONObject = try? JSONSerialization.jsonObject(with: JSONData, options: []), | |
let jsonData = try? JSONSerialization.data(withJSONObject: JSONObject, options: .prettyPrinted) else { | |
appendInterpolation("Invalid JSON data") | |
return | |
} | |
appendInterpolation("\n\(String(decoding: jsonData, as: UTF8.self))") | |
} | |
} | |
// Use | |
let jsonData = """ | |
{ | |
"name": "Wassily Kandinsky" | |
} | |
""".data(using: .utf8)! | |
print("The provided JSON is \(json: jsonData)") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment