0
0
JavascriptHow-ToBeginner · 3 min read

How to Pretty Print JSON in JavaScript: Simple Syntax & Examples

To pretty print JSON in JavaScript, use JSON.stringify(object, null, space) where space is the number of spaces for indentation. This formats the JSON string with line breaks and indentation for easy reading.
📐

Syntax

The syntax for pretty printing JSON in JavaScript uses the JSON.stringify method with three parameters:

  • value: The JavaScript object or array to convert to JSON.
  • replacer: Usually null, used to filter or modify values.
  • space: Number of spaces or a string used for indentation to format the output.
javascript
JSON.stringify(value, null, space)
💻

Example

This example shows how to pretty print a JavaScript object with 4 spaces indentation using JSON.stringify. The output is a readable JSON string with line breaks and spaces.

javascript
const obj = { name: "Alice", age: 30, skills: ["JavaScript", "HTML", "CSS"] };
const prettyJson = JSON.stringify(obj, null, 4);
console.log(prettyJson);
Output
{ "name": "Alice", "age": 30, "skills": [ "JavaScript", "HTML", "CSS" ] }
⚠️

Common Pitfalls

Common mistakes when pretty printing JSON include:

  • Omitting the space parameter, which results in a compact JSON string without line breaks.
  • Passing a non-null replacer unintentionally, which can filter out properties.
  • Using too large indentation which can make output hard to read.
javascript
const obj = { a: 1, b: 2 };

// Wrong: no indentation, hard to read
console.log(JSON.stringify(obj));

// Right: pretty print with 2 spaces
console.log(JSON.stringify(obj, null, 2));
Output
{"a":1,"b":2} { "a": 1, "b": 2 }
📊

Quick Reference

ParameterDescriptionExample
valueObject or array to convert{ name: "Bob" }
replacerFilter or modify values, usually nullnull
spaceIndentation spaces or string for formatting2 or "\t"

Key Takeaways

Use JSON.stringify(object, null, space) to pretty print JSON with indentation.
The space parameter controls the number of spaces or characters for indentation.
Omitting the space parameter outputs compact JSON without line breaks.
Avoid passing a replacer unless you want to filter or modify output properties.
Indentation improves readability but keep it reasonable for clarity.