How to Pretty Print JSON String in JavaScript

To pretty print a JSON string in JavaScript, you can use the “JSON.stringify()” method with its “optional third parameter”, which is the number of spaces to use for indentation.

Example

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.

Leave a Comment