Skip to content

Instantly share code, notes, and snippets.

@AmitaiB
Created December 9, 2020 18:58
Show Gist options
  • Save AmitaiB/ea7230166629e3a521510db89c50f38b to your computer and use it in GitHub Desktop.
Save AmitaiB/ea7230166629e3a521510db89c50f38b to your computer and use it in GitHub Desktop.
Pretty print JSON
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