Skip to content

Instantly share code, notes, and snippets.

@Edudjr
Created February 9, 2017 12:45
Show Gist options
  • Save Edudjr/cbd09220de89679f25eced359a6b8e08 to your computer and use it in GitHub Desktop.
Save Edudjr/cbd09220de89679f25eced359a6b8e08 to your computer and use it in GitHub Desktop.
Swift 3 JSON pretty printing
//Function to pretty-print Json Object in Swift 3
func prettyPrint(with json: [String:Any]) -> String{
let data = try! JSONSerialization.data(withJSONObject: json, options: .prettyPrinted)
let string = NSString(data: data, encoding: String.Encoding.utf8.rawValue)
return string as! String
}
@gurjitdhiman
Copy link

gurjitdhiman commented May 21, 2018

Updated to Pure Swift:

extension Dictionary {
    var prettyPrintedJSON: String? {
        do {
            let data: Data = try JSONSerialization.data(withJSONObject: self, options: .prettyPrinted)
            return String(data: data, encoding: .utf8)
        } catch _ {
            return nil
        }
    }
}

Usage:

let dictionaryObject: Dictionary<String, Any> = [
    "id" : 7,
    "name": "Gurjit Singh",
    "isIOSDeveloper": true
]
print(dictionaryObject.prettyPrintedJSON ?? "")

Output:

{

"id" : 7,

"name" : "Gurjit Singh",

"isIOSDeveloper" : true

}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment