Pretty-Printing with Space
You'll learn how to use the third parameter of JSON.stringify to format JSON output with readable indentation.
What Is the Space Parameter?
While the first parameter of JSON.stringify is the object to serialize and the second is the replacer, the third parameter controls indentation. When you pass a number or string to this parameter, JSON.stringify adds whitespace to make the output human-readable—perfect for debugging or logging.
Think of it like the difference between a paragraph with no line breaks versus neatly formatted text with proper spacing and indentation. Both contain the same information, but one is far easier to read.
Using a Number for Indentation
Pass a number (typically 2 or 4) to specify how many spaces to indent each level:
const user = {
name: "Alice",
age: 30,
hobbies: ["reading", "coding"]
};
// Compact (no space parameter)
console.log(JSON.stringify(user));
// {"name":"Alice","age":30,"hobbies":["reading","coding"]}
// Pretty-printed with 2 spaces
console.log(JSON.stringify(user, null, 2));
// {
// "name": "Alice",
// "age": 30,
// "hobbies": [
// "reading",
// "coding"
// ]
// }
Using a String for Indentation
You can also pass a string (like "\t" for tabs):
const data = { x: 1, y: 2 };
console.log(JSON.stringify(data, null, "\t"));
// {
// "x": 1,
// "y": 2
// }
The string can be up to 10 characters long; longer strings are truncated.
Key Takeaway: Use the third parameter of JSON.stringify to add indentation, making your JSON output readable for debugging and logging—just pass a number for spaces or a string like "\t" for tabs.