How to Pretty Print JSON String in JavaScript?
Last Updated :
21 Dec, 2024
Improve
To pretty print JSON, you can format JSON strings with proper indentation, making them easy to read and debug. In JavaScript, you can achieve this using JSON.stringify() with optional parameters to specify the indentation level.
- Pretty printing JSON adds line breaks and spaces for readability.
- It is commonly used for debugging or displaying JSON in a readable format.
- The JSON.stringify() method helps format JSON data with indentation.
const obj = { name: "Rahul", age: 30, city: "Mumbai" };
const pretty = JSON.stringify(obj, null, 2);
console.log(pretty);
Output
{ "name": "Rahul", "age": 30, "city": "Mumbai" }
How Pretty Printing Works
1. JSON.stringify() with Indentation
The JSON.stringify() method takes three arguments:
- The JSON object to stringify.
- A replacer function (optional).
- The number of spaces for indentation (optional).
2. Proper Spacing for Readability
By providing an indentation value, you can control the amount of spacing for nested elements.
Syntax
JSON.stringify(value[, replacer[, space]]);
- value: The JSON object or array to convert into a string.
- replacer (optional): A function or array to filter properties.
- space (optional): Number of spaces or a string for indentation.
Format JSON with 4 Spaces
const data = { name: "Anjali", profession: "Developer", skills: ["JavaScript", "Python"] };
const formatted = JSON.stringify(data, null, 4);
console.log(formatted);
Output
{ "name": "Anjali", "profession": "Developer", "skills": [ "JavaScript", "Python" ] }
Use Cases of Pretty Printing JSON
1. Debugging JSON Data
When dealing with complex JSON data, pretty printing helps debug issues effectively.
const raw = '{"name":"Vikas","details":{"age":25,"city":"Delhi"}}';
const obj = JSON.parse(raw);
console.log(JSON.stringify(obj, null, 2));
Output
{ "name": "Vikas", "details": { "age": 25, "city": "Delhi" } }
2. Saving Pretty JSON to Files
Pretty JSON can be written to files for better organization.
const fs = require('fs');
const obj = { name: "Pooja", age: 28, city: "Bangalore" };
fs.writeFileSync('data.json', JSON.stringify(obj, null, 2));
console.log('JSON saved in a pretty format.');
3. Display JSON in Web Applications
You can display formatted JSON in your web app using <pre> tags.
const jsonS = '{"name":"Amit","hobbies":["Cricket","Reading"]}';
const formatted = JSON.stringify(JSON.parse(jsonS), null, 2);
document.body.innerHTML = `<pre>${formatted}</pre>`;