How do I pretty print JSON in JavaScript?

To print JSON nicely in JavaScript, you can use the JSON.stringify(obj, replacer, space) method. The third parameter of the JSON.stringify() method specifies the number of spaces to use when outputting the JSON string. In this JavaScript Print JSON example, we use the JSON.stringify() method and specify the number of spaces in the third parameter to print the object in a human-readable format. Click Execute to run the JavaScript Pretty Print JSON Example online and see the result.
How do I pretty print JSON in JavaScript? Execute
let user = {"Id":4, "Customer":"Leo", "City":"Rome"};

console.log(JSON.stringify(user, null, 2));
Updated: Viewed: 734 times

What is JSON?

JSON (JavaScript Object Notation) is a lightweight text format for holding structured data format. JSON is often used to share information over the network in client/server and server/server communications. JSON itself includes no methods or functions; it's just a data storage format. JSON itself has no methods and does not support comments. JSON format came from JavaScript, but it is now actively used in almost all programming languages, including PHP, Python, Java, C++, C#, Go, and most of them, like Python, has built-in modules for working with JSON data.

JSON Example
{
  "Id": 78912,
  "Customer": "Jason Sweet",
  "Quantity": 1,
  "Price": 18.00
}

How pretty print JSON in JavaScript?

JavaScript has a built-in JSON.stringify(obj, replacer, space) method to convert objects to JSON and pretty-print the generated JSON string. The third argument, "space," defines the spacing and makes the JSON more human-readable:

JavaScript Pretty Print JSON Example
let data = {"Id":78912,"Customer":"Jason Sweet", "Quantity":1,"Price":18.00}

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

// output: 
// {
//   "Id": 78912,
//   "Customer": "Jason Sweet",
//   "Quantity": 1,
//   "Price": 18
// }

See also