Skip to content

Instantly share code, notes, and snippets.

@verebes1
Forked from cprovatas/Data+PrettyPrint.swift
Created March 20, 2019 17:01
Show Gist options
  • Save verebes1/a34f5b1549e665708349eb22b2934b59 to your computer and use it in GitHub Desktop.
Save verebes1/a34f5b1549e665708349eb22b2934b59 to your computer and use it in GitHub Desktop.
Pretty print JSON string from Data in Swift 4.1 (especially useful printing to Xcode console)
import Foundation
extension Data {
var prettyPrintedJSONString: NSString? { /// NSString gives us a nice sanitized debugDescription
guard let object = try? JSONSerialization.jsonObject(with: self, options: []),
let data = try? JSONSerialization.data(withJSONObject: object, options: [.prettyPrinted]),
let prettyPrintedString = NSString(data: data, encoding: String.Encoding.utf8.rawValue) else { return nil }
return prettyPrintedString
}
}
let str = "{\"foo\": \"bar\"}".data(using: .utf8)!.prettyPrintedJSONString!
debugPrint(str)
/* prints:
{
"foo" : "bar"
}
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment