jsonformattingpretty-printindentationtutorial

How to Format JSON Online: A Step-by-Step Guide

JSON Tools Team
7 min read

If you have ever received a JSON response from an API and found yourself staring at an unbroken wall of text, you already know the problem. Raw JSON returned by servers is almost always minified: every unnecessary space and line break has been stripped out to reduce payload size. That is great for network performance, but terrible for human readability.

Formatting JSON — also called pretty-printing — transforms that dense block into a clean, indented structure you can actually read and reason about. Whether you are debugging a REST API, reviewing a configuration file, or preparing data for documentation, knowing how to format JSON quickly is a fundamental developer skill.

In this guide, we will walk through exactly what JSON formatting is, how to do it online in seconds, and how to handle the edge cases that trip people up. We will also look at code examples you can adapt for your own projects.

What Is JSON Formatting?

JSON (JavaScript Object Notation) formatting is the process of adding consistent indentation, line breaks, and spacing to a JSON document so that its hierarchical structure becomes visually apparent. A formatted JSON document and a minified one are semantically identical — they contain exactly the same data. The only difference is whitespace.

Here is a quick example. This is minified JSON as you might receive it from an API:

{"users":[{"id":1,"name":"Alice","email":"alice@example.com","roles":["admin","editor"]},{"id":2,"name":"Bob","email":"bob@example.com","roles":["viewer"]}]}

And here is the same data after formatting with 2-space indentation:

{
  "users": [
    {
      "id": 1,
      "name": "Alice",
      "email": "alice@example.com",
      "roles": [
        "admin",
        "editor"
      ]
    },
    {
      "id": 2,
      "name": "Bob",
      "email": "bob@example.com",
      "roles": [
        "viewer"
      ]
    }
  ]
}

The formatted version makes it immediately obvious that there are two user objects, each with an id, name, email, and roles array. You can spot missing fields, typos, and structural problems at a glance.

Why Formatting JSON Matters

Faster Debugging

When an API returns an unexpected response, the first thing most developers do is inspect the JSON payload. If that payload is a single 5,000-character line, finding the problematic field is like searching for a needle in a haystack. Formatted JSON lets you scan the structure visually and locate issues in seconds.

Better Code Reviews

JSON configuration files (like package.json, tsconfig.json, or CI pipeline configs) appear regularly in pull requests. Consistently formatted JSON makes diffs cleaner and code reviews faster, because reviewers can focus on the actual changes rather than reformatting noise.

Cleaner Documentation

If you include JSON examples in API documentation, wikis, or README files, formatting is not optional — it is a requirement for readability. Unformatted examples will confuse your readers and undermine the credibility of your documentation.

How to Format JSON Online: Step by Step

The fastest way to format JSON is to use an online tool. No installation, no configuration — just paste, click, and copy. Here is how to do it with our JSON Formatter:

  1. Open the formatter. Navigate to the JSON Formatter tool in your browser.
  2. Paste your JSON. Copy your raw or minified JSON into the input editor on the left side. The editor accepts any valid JSON, from a simple key-value pair to a deeply nested document.
  3. Click "Format". The tool parses your JSON and applies consistent indentation. The formatted result appears instantly in the output panel.
  4. Choose your indentation. Prefer 4 spaces instead of 2? Tabs instead of spaces? Adjust the indentation setting to match your project's style guide.
  5. Copy the result. Click the copy button to place the formatted JSON on your clipboard, ready to paste into your code editor, documentation, or Slack message.

The entire process takes under ten seconds for most payloads. For very large JSON documents (several megabytes), the formatting may take a moment longer, but online tools like ours handle large files without issue.

Formatting JSON in Code

Sometimes you need to format JSON inside your application rather than manually pasting it into a tool. Every major language has built-in support for this.

JavaScript / Node.js

The JSON.stringify() method accepts a third argument that controls indentation:

const data = { name: "Alice", scores: [98, 87, 93], active: true };

// Pretty-print with 2-space indentation
const formatted = JSON.stringify(data, null, 2);
console.log(formatted);

This outputs:

{
  "name": "Alice",
  "scores": [
    98,
    87,
    93
  ],
  "active": true
}

The second argument to JSON.stringify() is a replacer function or array that lets you filter which keys are included. Passing null means "include everything." The third argument can be a number (spaces) or a string (like "\t" for tabs).

Python

Python's json module works similarly:

import json

data = {"name": "Alice", "scores": [98, 87, 93], "active": True}
formatted = json.dumps(data, indent=2, sort_keys=True)
print(formatted)

The sort_keys=True parameter alphabetically orders the keys, which can be helpful when you want deterministic output for diffing or version control.

Common Mistakes When Formatting JSON

1. Trying to Format Invalid JSON

Formatting tools parse JSON before they can indent it. If your JSON has syntax errors — a missing comma, a trailing comma, an unquoted key — the formatter will fail. Always validate your JSON first if the formatter throws an error. Most validation tools will point you to the exact line and character where the problem occurs.

2. Confusing JSON with JavaScript Objects

JSON is a strict subset of JavaScript object syntax. In JavaScript, you can write { name: 'Alice' } with unquoted keys and single-quoted strings. In JSON, keys must be double-quoted and strings must use double quotes: { "name": "Alice" }. If you paste a JavaScript object literal into a JSON formatter, it will reject it.

3. Including Comments

Standard JSON does not support comments. If you have JSON with // or /* */ comments (common in JSON5 or JSONC used by VS Code settings), a strict JSON formatter will fail. Strip comments before formatting, or use a tool that explicitly supports JSON5.

4. Inconsistent Indentation in Projects

When multiple developers format JSON with different settings (2 spaces vs. 4 spaces vs. tabs), version control diffs become noisy and hard to review. Agree on a project-wide standard and enforce it with your editor config or a pre-commit hook.

JSON Formatting Best Practices

  • Use 2-space indentation for web projects. It is the most common convention in the JavaScript ecosystem, matching the style used by npm, ESLint, and Prettier defaults.
  • Minify before sending over the network. Formatted JSON is for humans; minified JSON is for machines. Use a JSON minifier to strip whitespace before transmitting data in production.
  • Validate before formatting. Save yourself time by running your JSON through a validator first. A formatter cannot fix syntax errors — it can only restructure valid JSON.
  • Keep keys in a consistent order. While JSON technically does not define key order, maintaining alphabetical or logical ordering (id first, then name, then details) makes documents easier to scan.
  • Use your editor's built-in formatter. VS Code, IntelliJ, and Sublime Text all have JSON formatting shortcuts. For VS Code, press Shift+Alt+F (Windows) or Shift+Option+F (Mac) with a JSON file open.

Formatting vs. Minification: When to Use Which

A common question is when you should keep JSON formatted and when you should minify it. The answer is straightforward:

  • Format when the JSON will be read by humans: configuration files, documentation, log output during development, API response inspection.
  • Minify when the JSON will be consumed by machines: API responses in production, data stored in databases, payloads transmitted over the network.

In practice, most projects format JSON in their source code (for readability) and minify it at build time or runtime (for performance). This gives you the best of both worlds. You can easily switch between the two using our JSON Formatter and JSON Minifier tools.

Advanced: Filtering and Sorting Keys During Formatting

Sometimes you do not want to format the entire JSON document — you want to extract or reorder specific fields. The replacer parameter in JSON.stringify() lets you do exactly that.

const apiResponse = {
  id: 42,
  name: "Widget",
  internal_sku: "WDG-042-X",
  price: 29.99,
  debug_trace: "abc123",
  description: "A useful widget"
};

// Only include public fields
const publicFields = ["id", "name", "price", "description"];
const cleaned = JSON.stringify(apiResponse, publicFields, 2);
console.log(cleaned);

Output:

{
  "id": 42,
  "name": "Widget",
  "price": 29.99,
  "description": "A useful widget"
}

This is useful when you need to log API responses without exposing internal fields, or when you want to produce clean JSON documentation from a larger data structure.

Try It Now

Ready to format your JSON? Paste your raw or minified JSON into our free online JSON Formatter and get clean, indented output in one click. No sign-up required, and your data never leaves your browser.

If you suspect your JSON might have syntax errors, run it through the JSON Validator first to catch problems before formatting. And when you are ready to ship your formatted JSON to production, use the JSON Minifier to strip it back down to its most compact form.

Conclusion

JSON formatting is a small skill that pays large dividends. It makes debugging faster, code reviews smoother, and documentation clearer. Whether you use an online formatter for quick one-off tasks or JSON.stringify() in your code for programmatic formatting, the key is consistency: pick an indentation style, apply it everywhere, and your JSON will always be easy to read.

The next time you receive a blob of minified JSON, do not squint at it — format it. Your future self will thank you.