Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
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? 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!
/* prints:
"foo" : "bar"

This comment has been minimized.

Copy link

commented Sep 26, 2019

It works well, thanks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.