Skip to main content
Home

Trick with JSON in JavaScript

Loved this writeup by Eduardo Bouças on custom JSON serializers/de-serializers.

Little did I know that JSON.stringify() has a third argument (it comes after the serializer function, described by Eduardo), which gives you a way to pretty print the output! It can be an int, which describes how many spaces should be used as an indentation.

JSON.stringify({a: 1, b: 2, c: {d: 3}}, null, 2)

{
  "a": 1,
  "b": 2,
  "c": {
    "d": 3
  }
}

You can go even fancier than that, with a string -- which is going to be used in place of the white space:

JSON.stringify({a: 1, b: 2, c: {d: 3}}, null, '~>')

{
~>"a": 1,
~>"b": 2,
~>"c": {
~>~>"d": 3
~>}
}

Don't know where's this going to be useful, but it's fun, for the least. A complete description of the API is on MDN, of course.

Profile picture

Andrei Glingeanu's notes and thoughts. You should follow him on Twitter, Instagram or contact via email. The stuff he loves to read can be found here on this site or on goodreads. Wanna vent or buy me a coffee?