Created
May 23, 2018 15:52
-
Star
(122)
You must be signed in to star a gist -
Fork
(23)
You must be signed in to fork a gist
-
-
Save cprovatas/5c9f51813bc784ef1d7fcbfb89de74fe 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 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" | |
} | |
*/ | |
Great!
Yes! using NSString
its seems to be awesome 👏
Thank you
ty!!
Thank you
Swifty version
extension Encodable { var prettyPrintedJSONString: String? { let encoder = JSONEncoder() encoder.outputFormatting = .prettyPrinted guard let data = try? encoder.encode(self) else { return nil } return String(data: data, encoding: .utf8) ?? nil } }
Best option!! 😍
thanks
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@DevNebulae
NSString
intentional, note comment:/// NSString gives us a nice sanitized debugDescription