Question
How can I display JSON in JavaScript in a format that is easy for humans to read? I want the output to include indentation and whitespace, and I am also interested in ways to present it with colors or styling when shown in a browser.
Short Answer
By the end of this page, you will understand how to pretty-print JSON in JavaScript using JSON.stringify(), how indentation works, when formatting is useful, and how developers display readable JSON in consoles, web pages, and debugging tools.
Concept
JSON is a text format used to represent structured data such as objects, arrays, strings, numbers, booleans, and null. In JavaScript, JSON is often used for APIs, configuration, storage, and debugging.
When JSON is sent or stored, it is often compact:
{"name":"Ava","age":28,"skills":["JS","CSS"]}
This is valid, but not very comfortable to read. Pretty-printing means formatting JSON with line breaks and indentation so humans can scan it more easily:
{
"name": "Ava",
"age": 28,
"skills": [
"JS",
"CSS"
]
}
In JavaScript, the standard way to do this is with JSON.stringify(value, replacer, space).
The third argument, space, controls indentation:
2means indent nested levels by 2 spaces4means indent by 4 spaces"\t"means indent with tabs
Pretty-printing matters because it helps with:
- debugging API responses
- logging structured data
- showing JSON in admin tools or developer pages
- exporting readable configuration files
Important distinction:
- JavaScript object: a live in-memory value
- JSON string: text representation of data
JSON.stringify() converts a JavaScript value into a JSON string. If you want readable JSON, you usually stringify the object with indentation.
Mental Model
Think of raw JSON as a paragraph with no punctuation or line breaks. The information is there, but it is hard to scan.
Pretty-printing is like turning that paragraph into a neatly formatted outline:
- each nested level is indented
- related items are grouped visually
- line breaks separate sections
The data does not change. Only the presentation changes.
So the mental model is:
- object = the actual data
- pretty-printed JSON = a readable printed version of that data
Syntax and Examples
The main syntax is:
JSON.stringify(value, replacer, space)
Parameters
value: the JavaScript object or array to convertreplacer: usuallynullif you do not want custom filteringspace: number of spaces or a string used for indentation
Basic example
const data = {
name: "Ava",
age: 28,
active: true,
skills: ["JavaScript", "React"]
};
const pretty = JSON.stringify(data, null, 2);
console.log(pretty);
Output:
{
"name": "Ava"
Step by Step Execution
Consider this code:
const user = {
name: "Lina",
age: 31,
address: {
city: "Paris",
zip: "75000"
}
};
const result = JSON.stringify(user, null, 2);
console.log(result);
Step-by-step
useris created as a JavaScript object.JSON.stringify(user, null, 2)starts converting that object into a JSON string.- The
nullreplacer means no custom filtering or transformation is applied. - The
2tells JavaScript to indent nested levels using 2 spaces. - JavaScript walks through the object:
namebecomes a JSON string fieldagebecomes a number fieldaddressbecomes a nested JSON object
- Line breaks and spaces are inserted into the returned string.
resultnow contains a , not an object.
Real World Use Cases
Pretty-printed JSON is commonly used in practical development work.
API debugging
When testing a REST API, developers often inspect response data:
fetch("/api/user/42")
.then(response => response.json())
.then(data => console.log(JSON.stringify(data, null, 2)));
Admin dashboards
A dashboard might show raw API payloads or configuration objects for support teams.
Saving readable files
If an app exports settings to a file, pretty JSON is easier to review and edit.
Logging during development
Readable logs help developers inspect nested objects without confusion.
Teaching and documentation
Formatted JSON is easier to show in tutorials, docs, or error reports.
Real Codebase Usage
In real projects, developers usually use pretty-printed JSON in a few standard ways.
1. Debug logging
During development:
console.log(JSON.stringify(config, null, 2));
This is especially useful when normal console output collapses nested objects.
2. Conditional formatting
Pretty output is often used in development, while compact JSON is used in production for efficiency.
const json = isDevelopment
? JSON.stringify(data, null, 2)
: JSON.stringify(data);
3. Validation before display
If JSON comes from user input or an API as a string, developers parse it first and handle errors.
try {
const parsed = JSON.parse(rawJson);
console.log(JSON.stringify(parsed, null, 2));
} (error) {
.();
}
Common Mistakes
Mistake 1: Forgetting that JSON.stringify() returns a string
Broken expectation:
const obj = { name: "Sam" };
const pretty = JSON.stringify(obj, null, 2);
console.log(pretty.name); // undefined
Why it happens:
prettyis a string, not an object
How to avoid it:
- Keep the original object if you still need property access
const obj = { name: "Sam" };
const pretty = JSON.stringify(obj, null, 2);
console.log(obj.name); // "Sam"
Mistake 2: Using innerHTML to display JSON
Broken approach:
Comparisons
| Concept | What it does | When to use |
|---|---|---|
JSON.stringify(obj) | Converts to compact JSON text | Sending or storing data efficiently |
JSON.stringify(obj, null, 2) | Converts to readable JSON text | Debugging, display, logs, exports |
console.log(obj) | Logs a live object view in many environments | Quick inspection during development |
JSON.parse(text) | Converts JSON text back into a JavaScript value | Reading JSON input |
console.log(obj) vs JSON.stringify(obj, null, 2)
console.log(obj)may show an expandable object in dev toolsJSON.stringify(obj, null, 2)gives you exact formatted text
Cheat Sheet
JSON.stringify(value, replacer, space)
Most common pretty-print form
JSON.stringify(data, null, 2)
Meaning of arguments
value: object or array to convertreplacer:nullfor no filteringspace: indentation, such as2,4, or"\t"
Examples
JSON.stringify(data)
- compact JSON
JSON.stringify(data, null, 2)
- pretty JSON with 2 spaces
FAQ
How do I pretty-print JSON in JavaScript?
Use:
JSON.stringify(data, null, 2)
The 2 adds two-space indentation.
How do I use tabs instead of spaces?
Pass "\t" as the third argument:
JSON.stringify(data, null, "\t")
Why is my formatted JSON showing as one line in HTML?
HTML collapses whitespace by default. Put the output inside a <pre> element or use CSS like white-space: pre;.
Does JSON.stringify() add syntax highlighting?
No. It only creates text with indentation and line breaks. Use CSS or a syntax-highlighting library for colors.
Can I pretty-print a JSON string I already have?
Yes, parse it first, then stringify it again:
const pretty = JSON.stringify(.(rawJson), , );
Mini Project
Description
Build a small JSON viewer that takes a JavaScript object and displays it in a readable format on a web page. This demonstrates how to convert data into pretty-printed JSON and render it safely for human readers.
Goal
Create a page that shows formatted JSON with preserved indentation and line breaks.
Requirements
[ "Create a JavaScript object with nested data.", "Convert the object into pretty-printed JSON using two-space indentation.", "Display the result on the page so whitespace is preserved.", "Use safe text rendering instead of HTML injection." ]
Keep learning
Related questions
Deep Cloning Objects in JavaScript: Methods, Trade-offs, and Best Practices
Learn how to deep clone objects in JavaScript, compare structuredClone, JSON methods, and recursive approaches with examples.
Get Screen, Page, and Browser Window Size in JavaScript
Learn how to get screen size, viewport size, page size, and scroll position in JavaScript across major browsers with clear examples.
How JavaScript Closures Work: A Beginner-Friendly Guide
Learn how JavaScript closures work with simple explanations, examples, common mistakes, and practical use cases for real code.