Created
December 9, 2020 18:58
-
-
Save AmitaiB/ea7230166629e3a521510db89c50f38b to your computer and use it in GitHub Desktop.
Pretty print JSON
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
class PrettyPrinter { | |
static func print(json tryJSON: Any) -> String { | |
var result = "\(tryJSON)" | |
do { | |
guard JSONSerialization.isValidJSONObject(tryJSON) else { return result } | |
let data = try JSONSerialization.data(withJSONObject: tryJSON, options: .prettyPrinted) | |
guard let string = String(data: data, encoding: .utf8) else { return result } | |
result = string | |
} | |
catch { | |
Swift.print("\nJSON printing error, falling back on `description` method\n") | |
} | |
return result | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment