Pretty Print JSON Programmatically using JavaScript

featured Image

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

Related Posts

featured Image

Get the 10 characters from a string using JavaScript.

Here, in this article we will learn how to get the first 10 character from any string using JavaScript. Here we will be using JavaScript’s String method substring. What is…

Read more
featured Image

Convert date to long date format using JavaScript

In this article we will look into how to convert a date to a long date format using JavaScript. To convert it to a long format we will be using…

Read more
featured Image

Prevent body from scrolling when a modal is opened

Here, in this article, we will learn how to prevent the body from scrolling when a modal or a pop-up is opened using JavaScript. The scroll event is not cancelable….

Read more