How to pretty-print a JSON object with JavaScript
As a JavaScript developer, I've used JSON.stringify() several times, especially for serializing the data before sending the payload to the backend.
But JSON.stringify() has much more to it. It simply does not convert a JavaScript object or a value to a JSON string but it also provides options to replace values using a replacer function (which is out of scope for this article) as well as space option which lets you define the tab space you wish to pass which will indent and pretty-print the stringified JSON.
As mentioned above, JSON.stringify() accepts three parameters, i.e, value, replacer & space where replacer and space are optional.
If you skip the optional parameters, the JSON.stringify() function will end up returning a JSON string which is not easy to read.
To improve the readability, we can pass a number as the third argument (space), which represents the total number of white spaces to insert.
Note space argument accepts a max number of 0 to 10 or a string which can be used as white space.
const myObj = {
"people": [
{
"name": "Mark Vande Hei",
"craft": "ISS"
},
{
"name": "Oleg Novitskiy",
"craft": "ISS"
},
{
"name": "Pyotr Dubrov",
"craft": "ISS"
}
]
};
// serialize myObj
const str = JSON.stringify(myObj, null, 2);
// pretty print
console.log(str);
The above code will pretty-print the JSON object as a string like:
{
"people": [
{
"name": "Mark Vande Hei",
"craft": "ISS"
},
{
"name": "Oleg Novitskiy",
"craft": "ISS"
},
{
"name": "Pyotr Dubrov",
"craft": "ISS"
}
]
}
Thus, JSON.stringify() helps you format the serialized JSON in a readable format. If we skip passing the value to the space argument of JSON.stringify() then the console will output something like below (scroll horizontally):
{"people":[{"name":"Mark Vande Hei","craft":"ISS"},{"name":"Oleg Novitskiy","craft":"ISS"},{"name":"Pyotr Dubrov","craft":"ISS"}]}
The above is definitely not readable :)
References
You could check out a few references related to the above: