-
-
Save arturlector/be04fdcc7dc0658f3c8c5f71b85b9f96 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)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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