Search code examples
jsonswiftencodingjsonencoder

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)


Solution

  • 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"}