Table of Contents
Recently, while working on a DynamoDB editing tool, I needed to improve the look of my editor. The JSON was all in one line and it’s hard to see the values/properties that way.
It turned out, pretty print JSON is quite simple with JSON.stringify. Let’s see how to do that.
The JSON.stringify function
I’ve been using JSON.stringify for years and the only way I knew was to pass the object I need to turn to string into the function:
Little did I know, that it is possible to pass the other two parameters into this function. One is a replacer and one is the number of spaces used for indentation.
JSON.stringify(value, replacer, space)
You can also pass a string value to the third parameter. This value will be used to indent lines when printing.
Details are available here on MDN.
Pretty Print JSON with JSON.stringify
Let’s see how to pretty print JSON in action.
As you can see, I’m able to pretty print my JSON with 4 and 10 indentations.
And of course, as mentioned, you can use a string instead of a number for the third parameter:
I build softwares that solve problems. I also love writing/documenting things I learn/want to learn.