Last active
June 7, 2022 14:46
-
-
Save andreabusi/8c7994a0dc19dd0d6cc7f97ec13b63a9 to your computer and use it in GitHub Desktop.
Swift - Convert JSON dictionary into a pretty printed string
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
public extension Dictionary { | |
/// Returns a pretty printed JSON version of the current dictionary. | |
/// String uses white space and indentation to make the resulting data more readable. | |
var prettyPrintedJson: String { | |
do { | |
let data = try JSONSerialization.data(withJSONObject: self, options: [.withoutEscapingSlashes, .prettyPrinted]) | |
return String(data: data, encoding: .utf8) ?? "" | |
} catch { | |
return "" | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This extension allows to pretty print a JSON dictionary, removing type definition used by Swift.
This is a JSON printed using standard string interpolation:
And this is the result using the
prettyPrintedJson
extension: