How to Pretty Print JSON String in JavaScript

To pretty print a JSON string in JavaScript, use the JSON.stringify() method and pass the optional third parameter non-zero number, which is the number of spaces to use for indentation.

Why pretty print JSON?

JSON strings are not readable by humans. To make JSON readable, you need to generate a pretty JSON string.

const data = {
  name: "Niva Shah",
  age: 30,
  address: {
    street: "123 First St",
    city: "Mumbai",
    country: "India"
  }
};

const jsonString = JSON.stringify(data);
console.log(jsonString);

console.log("After pretty print")

const prettyJsonString = JSON.stringify(data, null, 2);
console.log(prettyJsonString);

Output

{"name":"Niva Shah","age":30,"address":
  {"street":"123 First St","city":"Mumbai","country":"India"}}

After pretty print

{
 "name": "Niva Shah",
 "age": 30,
 "address": {
   "street": "123 First St",
   "city": "Mumbai",
   "country": "India"
 }
}

In this code example, the JSON.stringify() method is called with the data object, null for the replacer function, and 2 for the indentation. The resulting prettyJsonString variable contains the JSON string formatted with “2” spaces for indentation, making it easier to read.

Pretty print an existing JSON string

const str = '{"rollno": 21, "name": "Krunal Lathiya", "college": "VVP College"}';

const obj = JSON.parse(str);

console.log(JSON.stringify(obj, null, 2));

Output

{
  "rollno": 19,
  "name": "Niva Shah",
  "college": "IIT"
}

Pretty print JavaScript object to JSON string

const obj = {rollno: 19, name: "Niva Shah", college: "IIT"};

console.log(JSON.stringify(obj, null, 2));

Output

{
  "rollno": 19,
  "name": "Niva Shah",
  "college": "IIT"
}

That’s it.