Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elegant way to view JSONEncode() output in swift

var test = [String : String] ()
test["title"] = "title"
test["description"] = "description"

let encoder = JSONEncoder()
let json = try? encoder.encode(test)

How can I see the output of the json?

If I use print(json) the only thing I get is Optional(45 bytes)

like image 623
Amir Avatar asked Jul 10 '17 18:07

Amir


2 Answers

The encode() method returns Data containing the JSON representation in UTF-8 encoding. So you can just convert it back to a string:

var test = [String : String] ()
test["title"] = "title"
test["description"] = "description"

let encoder = JSONEncoder()
if let json = try? encoder.encode(test) {
    print(String(data: json, encoding: .utf8)!)
}

Output:

{"title":"title","description":"description"}
like image 96
Martin R Avatar answered Nov 09 '22 20:11

Martin R


With Swift 4, String has a initializer called init(data:encoding:). init(data:encoding:) has the following declaration:

init?(data: Data, encoding: String.Encoding)

Returns a String initialized by converting given data into Unicode characters using a given encoding.


The following Playground snippets show how to use String init(data:encoding:) initializer in order to print a JSON data content:

import Foundation

var test = [String : String]()
test["title"] = "title"
test["description"] = "description"

let encoder = JSONEncoder()
if let data = try? encoder.encode(test),
    let jsonString = String(data: data, encoding: .utf8) {
    print(jsonString)
}

/*
 prints:
 {"title":"title","description":"description"}
 */

Alternative using JSONEncoder.OutputFormatting set to prettyPrinted:

import Foundation

var test = [String : String]()
test["title"] = "title"
test["description"] = "description"

let encoder = JSONEncoder()
encoder.outputFormatting = .prettyPrinted

if let data = try? encoder.encode(test),
    let jsonString = String(data: data, encoding: .utf8) {
    print(jsonString)
}

/*
 prints:
 {
   "title" : "title",
   "description" : "description"
 }
 */
like image 5
Imanou Petit Avatar answered Nov 09 '22 20:11

Imanou Petit