Skip to content

Instantly share code, notes, and snippets.

@mteera
Created January 26, 2018 14:17
Show Gist options
  • Save mteera/8e724fb548577781cbd645992ea78637 to your computer and use it in GitHub Desktop.
Save mteera/8e724fb548577781cbd645992ea78637 to your computer and use it in GitHub Desktop.
A function to print JSON objects for readability.
func JSONStringify(value: AnyObject, prettyPrinted: Bool = true) -> String {
let options = prettyPrinted ? JSONSerialization.WritingOptions.prettyPrinted : nil
if JSONSerialization.isValidJSONObject(value) {
do {
let data = try JSONSerialization.data(withJSONObject: value, options: options!)
if let string = NSString(data: data, encoding: String.Encoding.utf8.rawValue) {
return string as String
}
} catch {
return ""
}
}
return ""
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment