Skip to content

Instantly share code, notes, and snippets.

@andreabusi
Last active June 7, 2022 14:46
Show Gist options
  • Save andreabusi/8c7994a0dc19dd0d6cc7f97ec13b63a9 to your computer and use it in GitHub Desktop.
Save andreabusi/8c7994a0dc19dd0d6cc7f97ec13b63a9 to your computer and use it in GitHub Desktop.
Swift - Convert JSON dictionary into a pretty printed string
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 ""
}
}
}
@andreabusi
Copy link
Author

This extension allows to pretty print a JSON dictionary, removing type definition used by Swift.

This is a JSON printed using standard string interpolation:

[AnyHashable("aps"): {
    alert =     {
        body = "Here's to the crazy ones. The misfits. The rebels. The troublemakers. The round pegs in the square holes.";
        title = "Think different";
    };
    "content-available" = 1;
    "mutable-content" = 1;
}, AnyHashable("data"): {
}]

And this is the result using the prettyPrintedJson extension:

{
  "aps" : {
    "alert" : {
      "title" : "Think different",
      "body" : "Here's to the crazy ones. The misfits. The rebels. The troublemakers. The round pegs in the square holes."
    },
    "mutable-content" : 1,
    "content-available" : 1
  },
  "data" : {

  }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment