Pretty Print JSON Programmatically using JavaScript

In this tutorial, we will learn how to beautify a JSON string programmatically in JavaScript.

To pretty-print a JSON, you have to convert it to an object first and then convert it back into a string using JSON stringify pretty-print.

This is a normal-looking JSON string.

'{"name":"Elmo","occupation":"sleeping"}'

It’s easy to read when it’s small. However, if the JSON string contains lots of data it is very hard to read or understand the data.

So to make it easy for human readability, we can pretty-print/beautify it using JSON.stringify() method.

The JSON.stringify() method converts a JSON object to a JSON string. And this method also allows us to pass two more arguments: replacer and space.

Syntax:

JSON.stringify(value, replacer, space)

The space argument lets us prettify our JSON string. We can pass a number or string as the value.

If we pass it as a number, will indicate the number of space characters to insert white space in front of each JSON property. Usually is like 2 or 4 and the limit is up to 10.

Example

const jsonStr = '{"name":"Elmo","occupation":"sleeping"}'
JSON.stringify(JSON.parse(jsonStr), null, 4);

Output:

{
    "name": "Elmo",
    "occupation": "sleeping"
}

In the above code, we have converted the JSON string to an object using JSON.parse() and then convert it back to string using JSON.stringify() to display it in pretty-print format.

If we pass an empty string, the successive levels will be divided by the string (here with an empty space in front).

JSON.stringify(obj, null, ' ')

Output:

{
 "name": "Elmo",
 "occupation": "sleeping"
}

We can also pass a tab character to mimics the standard pretty-print appearance:

JSON.stringify(obj, null, 't')

Output:

{
    "name": "Elmo",
    "occupation": "sleeping"
}

You can read more about the JSON.stringify() method and the use of all the arguments from this article.

Related Topics:

How To Covert JavaScript Object To JSON String

Scroll to Top