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"))
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. Andspace
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.
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.