Beautify or pretty print JSON programmatically in JavaScript


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

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 obj = '{"name":"Elmo","occupation":"sleeping"}'

JSON.stringify(obj, null, 4);

Output:

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

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:

Difference Between JSON.Stringify() And JSON.Parse() In JSON

How to convert a JSON string into a JavaScript object

How To Covert JavaScript Object To JSON String


💾 Recommended Articles