How To Pretty Print JSON in Javascript/TypeScript


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:

JSON.stringify regular use

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.

pretty print json with indentation 4
pretty print json with indentation 10

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:

Use string instead of number in stringify


In this post, I’ve shown you how to pretty print JSON in TypeScript/Javascript.

Leave a Comment