Question

How to Pretty-Print JSON in JavaScript

javascriptjsonpretty-print

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:

  • 2 means indent nested levels by 2 spaces
  • 4 means 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
Take Quiz

Syntax and Examples

The main syntax is:

JSON.stringify(value, replacer, space)

Parameters

  • value: the JavaScript object or array to convert
  • replacer: usually null if you do not want custom filtering
  • space: 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",
  "age": 28,
  "active": true,
  "skills": [
    "JavaScript",
    "React"
  ]
}

Using tabs instead of spaces

const pretty = JSON.stringify(data, null, "\t");
console.log(pretty);

Displaying JSON on a web page

const data = {
  user: "Ava",
  role: "admin"
};

document.getElementById("output").textContent = JSON.stringify(data, null, 2);

This works well with a <pre> element because <pre> preserves whitespace and line breaks.

Colored or styled display

JSON.stringify() only creates formatted text. It does not add colors. For colors in a browser, developers usually:

  • put the JSON into a <pre> block
  • apply CSS styles
  • or use a syntax-highlighting library

Example idea:

const jsonText = JSON.stringify(data, null, 2);
document.getElementById("output").textContent = jsonText;

Then CSS can style the container, though not individual JSON tokens unless you add extra parsing or a library.

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

  1. user is created as a JavaScript object.
  2. JSON.stringify(user, null, 2) starts converting that object into a JSON string.
  3. The null replacer means no custom filtering or transformation is applied.
  4. The 2 tells JavaScript to indent nested levels using 2 spaces.
  5. JavaScript walks through the object:
    • name becomes a JSON string field
    • age becomes a number field
    • address becomes a nested JSON object
  6. Line breaks and spaces are inserted into the returned string.
  7. result now contains a string, not an object.
  8. console.log(result) prints the readable JSON text.

Result:

{
  "name": "Lina",
  "age": 31,
  "address": {
    "city": "Paris",
    "zip": "75000"
  }
}

Important detail

After stringifying, you cannot access properties from result like this:

console.log(result.name); // undefined

That is because result is text. If you need an object again, you would use JSON.parse(result).

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.

Take Quiz

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));
} catch (error) {
  console.error("Invalid JSON");
}

4. Rendering in UI components

A common pattern is to render JSON inside a <pre> element so spacing is preserved.

5. Custom filtering with replacer

Sometimes developers remove sensitive fields before printing:

const user = {
  name: "Ava",
  password: "secret123",
  role: "admin"
};

const safe = JSON.stringify(user, (key, value) => {
  if (key === "password") return undefined;
  return value;
}, 2);

This pattern is useful for logging and debugging without exposing secrets.

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:

  • pretty is 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:

document.getElementById("output").innerHTML = JSON.stringify({ x: 1 }, null, 2);

Why it can be a problem:

  • innerHTML is for HTML, not plain text
  • it can create security issues if the content is untrusted

Better approach:

document.getElementById("output").textContent = JSON.stringify({ x: 1 }, null, 2);

Mistake 3: Expecting colors from JSON.stringify() alone

const text = JSON.stringify(data, null, 2);

This only creates formatted text. It does not add syntax coloring.

How to avoid confusion:

  • use CSS for container styling
  • use a syntax-highlighting library if token-level colors are needed

Mistake 4: Stringifying values that JSON does not represent normally

Example:

const data = {
  fn: () => 123,
  missing: undefined
};

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

Some values are omitted or changed when converted to JSON.

How to avoid surprises:

  • remember JSON supports objects, arrays, strings, numbers, booleans, and null
  • do not expect functions or undefined to appear normally in JSON output

Mistake 5: Parsing invalid JSON strings

Broken code:

const raw = "{name: 'Ava'}";
JSON.parse(raw);

Why it fails:

  • valid JSON requires double-quoted property names and string values

Correct JSON:

const raw = '{"name": "Ava"}';
const data = JSON.parse(raw);

Comparisons

ConceptWhat it doesWhen to use
JSON.stringify(obj)Converts to compact JSON textSending or storing data efficiently
JSON.stringify(obj, null, 2)Converts to readable JSON textDebugging, display, logs, exports
console.log(obj)Logs a live object view in many environmentsQuick inspection during development
JSON.parse(text)Converts JSON text back into a JavaScript valueReading JSON input

console.log(obj) vs JSON.stringify(obj, null, 2)

  • console.log(obj) may show an expandable object in dev tools
  • JSON.stringify(obj, null, 2) gives you exact formatted text

Compact JSON vs pretty JSON

FormatExample useBenefitTrade-off
CompactAPI responses, storageSmaller sizeHarder to read
PrettyLogs, docs, admin toolsEasier for humansLarger size

Spaces vs tabs for indentation

IndentationExampleUse case
2Two spacesVery common default
4Four spacesMore visual separation
"\t"Tab characterIf your team prefers tabs
Take Quiz

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 convert
  • replacer: null for no filtering
  • space: indentation, such as 2, 4, or "\t"

Examples

JSON.stringify(data)
  • compact JSON
JSON.stringify(data, null, 2)
  • pretty JSON with 2 spaces
JSON.stringify(data, null, "\t")
  • pretty JSON with tabs

Displaying in HTML

Use textContent and a <pre> element to preserve formatting.

preElement.textContent = JSON.stringify(data, null, 2);

Remember

  • JSON.stringify() returns a string
  • it formats text, not colors
  • use JSON.parse() to convert JSON text back into data
  • functions and undefined are not represented normally in JSON
  • pretty JSON is best for humans, compact JSON is best for transfer/storage

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(JSON.parse(rawJson), null, 2);

What if the JSON is invalid?

JSON.parse() will throw an error. Use try...catch when handling unknown input.

Is pretty-printed JSON slower or bigger?

It is bigger because it contains extra spaces and line breaks. That is usually fine for debugging and display, but compact JSON is better for network transfer.

Take Quiz

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." ]

Take Quiz

Keep learning

Related questions

View more