Skip to content

Pretty print a JSON object with console.log

nodejavascript

Ever squinted at a JSON object printed in our favorite debugger, the console? Well, here’s how to make it easier to read:

const dog = {"name": "Rudolf", "breed": "Belgian Shepard", "prefPronoun": "🐶"}
console.log(JSON.stringify(dog, null, "\t"))

How JSON.stringify() pretty print works

What happens here is that we use a JSON.stringify method to parse a JavaScript object into a JSON string. The syntax is:

JSON.stringify(value, replacer, space)

Where:

  • value is the JavaScript option and is mandatory.
  • replacer is an optional function to change the behavior of the stringification process. And
  • space is an object used to insert whitespaces for better readability.

So in the example above, we have no replacer and for whitespaces we use the special character \t which is a special character for introducing a tab.

Open the console and try it out for yourself.

the util.inspect() alternative

In node.js you can do something similar with util.inspect(). But in this case you have to import util. JSON.stringify() is available without any imports.

Get updates for FREE

Put in your best email and I'll send you new articles, like this one, the moment they come out. ✌️

    Won't send you spam. Unsubscribe at any time.