JSON

How to Format JSON: The Complete Developer Guide (2026)

2026-05-03 · 8 min read · Format JSON free →

Raw JSON from an API response looks like this: {"user":{"id":42,"name":"Maria","roles":["admin","editor"],"active":true}}. One long line, no whitespace, impossible to read at a glance. Formatting it — also called pretty-printing or beautifying — adds indentation and line breaks so the structure becomes immediately clear. This guide explains everything about JSON formatting: how to do it instantly online, how to do it in code, what to watch out for, and why it matters beyond just readability.

What is JSON Formatting?

JSON formatting transforms minified or compact JSON into an indented, human-readable layout. The content of the JSON is identical — the data does not change. Only whitespace is added. A formatter adds a newline after every property, indents nested objects and arrays, and aligns keys so the hierarchy of the data structure is visually obvious.

The reverse operation — removing all non-essential whitespace — is called minifying or compressing JSON. Minified JSON is smaller in bytes, which is why APIs return it. Formatted JSON is easier to read and debug, which is why developers format it locally before working with it.

Format JSON Instantly Online

The fastest way is to use ToolPry's JSON Formatter — paste your JSON, it formats and validates in real time with no button click required. It runs entirely in your browser: your data never leaves your machine. There is no sign-up, no file size limit, and no usage cap.

For API responses specifically, open your browser's Network tab (F12), click the API call, and look at the Response or Preview tab. Modern browsers already format JSON responses for you in the Preview tab. If you need to copy and inspect the data further, paste it into the formatter.

Format JSON in Your Terminal

If you are working with JSON files or API responses on the command line, these tools handle formatting without any browser needed.

Using Python (built-in, no install needed)

cat data.json | python3 -m json.tool

# Format and save to a new file
python3 -m json.tool data.json > formatted.json

# Format JSON from a curl API call directly
curl -s https://api.example.com/users | python3 -m json.tool

Using jq (the gold standard for JSON on the command line)

# Install: brew install jq  (Mac) or apt install jq  (Ubuntu)

# Format (pretty-print)
cat data.json | jq .

# Format + filter: get only the "users" array
cat data.json | jq '.users'

# Format API response and save
curl -s https://api.example.com/users | jq . > users-formatted.json

Using Node.js

node -e "const fs=require('fs'); const d=JSON.parse(fs.readFileSync('data.json')); console.log(JSON.stringify(d,null,2))"

Format JSON in Code

Every major language has a built-in way to format JSON with indentation. The key is the indent parameter — set it to 2 or 4 spaces depending on your style preference.

JavaScript / Node.js

const data = { name: "Maria", roles: ["admin", "editor"] };

// JSON.stringify(value, replacer, indent)
const formatted = JSON.stringify(data, null, 2);
console.log(formatted);
// {
//   "name": "Maria",
//   "roles": [
//     "admin",
//     "editor"
//   ]
// }

// Compact (minified)
const minified = JSON.stringify(data);
// {"name":"Maria","roles":["admin","editor"]}

Python

import json

data = {"name": "Maria", "roles": ["admin", "editor"]}

# Format with 2-space indent
formatted = json.dumps(data, indent=2)
print(formatted)

# Format and sort keys alphabetically
formatted_sorted = json.dumps(data, indent=2, sort_keys=True)

# Format a JSON file
with open("data.json") as f:
    data = json.load(f)
with open("formatted.json", "w") as f:
    json.dump(data, f, indent=2)

PHP

$data = ["name" => "Maria", "roles" => ["admin", "editor"]];
$formatted = json_encode($data, JSON_PRETTY_PRINT);
echo $formatted;

Go

import (
    "encoding/json"
    "fmt"
)

data := map[string]interface{}{"name": "Maria", "age": 30}
formatted, err := json.MarshalIndent(data, "", "  ")
if err == nil {
    fmt.Println(string(formatted))
}

JSON Formatting vs JSON Validation

These are related but different operations. Formatting arranges valid JSON into a readable layout. Validation checks whether the JSON is syntactically correct — it has matching braces, properly quoted keys, no trailing commas, no comments, and valid values.

Most formatters (including ToolPry's) validate at the same time. If your JSON has a syntax error, the formatter will refuse to format it and show you the exact location of the problem. This makes formatting a useful debugging step: if the formatter rejects your JSON, it tells you immediately where the error is.

Common validation errors you will encounter: trailing commas after the last property (valid JavaScript, invalid JSON), single quotes instead of double quotes, unquoted keys, comments (not allowed in JSON), and undefined values (use null instead). All of these are caught immediately by a validator.

When to Minify vs When to Format

Format JSON when you are debugging, reading API responses, writing documentation, reviewing data structure, or checking what a database query returned. The goal is human readability.

Minify JSON for production API responses, configuration files embedded in builds, and anywhere that network payload size matters. Removing whitespace can reduce JSON size by 20–40% depending on the data. For high-traffic APIs handling thousands of requests per second, this translates to meaningful bandwidth and infrastructure savings.

A good workflow: develop and debug with formatted JSON, but serve minified JSON in production. Most HTTP frameworks have middleware or serializer options to control this automatically — Express.js has app.set('json spaces', 2) for development, and most production setups leave this unset to default to minified output.

JSON Formatting Best Practices

Consistent indentation: Pick 2 or 4 spaces and stick to it across your project. Most style guides (Google, Airbnb) use 2 spaces for JSON. Tabs are valid but cause alignment issues in different editors.

Sort keys for diffs: When storing JSON in version control, sort keys alphabetically. This prevents meaningless diffs when the same object is serialized in a different order. Use sort_keys=True in Python or a custom replacer in JavaScript.

Use a formatter in CI: Add a JSON formatting check to your CI pipeline. Tools like Prettier enforce consistent formatting and fail the build if files are not formatted. This prevents formatting debates in code reviews and keeps JSON files consistent across the team.

Validate before deployment: Never deploy a configuration file without validating it first. A syntax error in a JSON config file can crash your entire application on startup. Paste it into the JSON Formatter or run python3 -m json.tool config.json before every deploy.

Tree view for deep nesting: When working with deeply nested JSON (5+ levels deep), a tree view formatter is often more useful than indented text. ToolPry's formatter includes a tree view mode that lets you collapse and expand individual nodes, making it easy to navigate large API responses without getting lost in the indentation.

Quick tip: In VS Code, you can format any open JSON file with Shift+Alt+F (Windows/Linux) or Shift+Option+F (Mac). This uses the built-in JSON formatter which also validates the file.

Handling Large JSON Files

Browser-based formatters can struggle with very large JSON files (10MB+). The page may become unresponsive while the formatter processes the data. For large files, use a command-line tool instead — jq can process gigabyte-sized JSON files efficiently because it streams the data rather than loading it entirely into memory.

If you only need to inspect part of a large JSON file, jq lets you filter to just the section you care about: cat large.json | jq '.data.users[0:10]' extracts the first 10 items from the users array without loading the rest of the file into your browser.

For JSON files generated by databases or log aggregators, consider whether JSON is the right format at all. Files over 50MB are often better served by NDJSON (Newline Delimited JSON — one JSON object per line) which is much easier to process with streaming parsers and command-line tools like jq --stream.

JSON Formatting in Popular Editors

Every modern code editor has built-in or plugin-based JSON formatting. Knowing the keyboard shortcuts saves time every day.

VS Code: Open any .json file and press Shift+Alt+F on Windows/Linux or Shift+Option+F on Mac. VS Code also formats on save if you add "editor.formatOnSave": true to your settings. The built-in formatter validates as it formats — if your JSON has a syntax error, it highlights the problem rather than attempting to format broken JSON.

JetBrains IDEs (IntelliJ, WebStorm, PyCharm): Press Ctrl+Alt+L on Windows/Linux or Cmd+Option+L on Mac to reformat any file. JetBrains IDEs understand JSON natively and offer configurable indent sizes per project.

Sublime Text: The built-in package does not format JSON, but the Pretty JSON plugin (install via Package Control) adds Ctrl+Alt+J formatting. Alternatively, pipe through Python: open the terminal panel and run python3 -m json.tool on the selected text.

Vim/Neovim: With the jq command installed, format the current file with :%!jq .. For a single selected block: visually select, then :!jq .. The prettier.nvim plugin handles this automatically for JSON files.

Frequently Asked Questions

Does formatting change the meaning of JSON?

No. Formatting only adds or removes whitespace between tokens. The actual data — keys, values, nesting structure, data types — is completely unchanged. A JSON parser treats {"a":1} and a fully indented multi-line version as identical inputs. Whitespace between tokens is always ignored by JSON parsers.

What is the difference between 2-space and 4-space indentation?

It is purely a style preference. Two-space indentation produces more compact output that is easier to see in full on screen. Four-space indentation produces more visually distinct nesting levels that some developers find easier to scan. Neither is more correct. Pick one and configure your editor and Prettier to enforce it consistently. The Google JSON Style Guide recommends 2 spaces.

Why does my formatter say the JSON is invalid when it looks correct?

The most common reasons: a trailing comma after the last property, single quotes instead of double quotes, an unquoted key, or a comment. Paste the JSON into ToolPry's JSON Formatter for an exact error location. It often helps to look at the character immediately before the position reported in the error message — that is almost always where the actual mistake is, not at the position itself.

Can I format JSON with comments?

Standard JSON does not support comments. If your file contains comments (using // or /* */), it is JSONC (JSON with Comments), a non-standard extension supported by VS Code and some other tools. Standard JSON formatters will reject it. Either remove the comments before formatting, or use a JSONC-aware tool. VS Code's built-in formatter handles JSONC files when the file extension is .jsonc or when the language mode is set to JSON with Comments.

How do I format JSON in a CI/CD pipeline?

Use Prettier with a .prettierrc file that sets "parser": "json" and your preferred tab width. Add a Prettier format check step to your CI pipeline: npx prettier --check "**/*.json". This fails the build if any JSON file is not correctly formatted, preventing formatting inconsistencies from being merged. Alternatively, python3 -m json.tool validates JSON files and exits with a non-zero code if invalid — useful as a lightweight CI check without installing Node.js.

What is the fastest way to format a large JSON API response?

Copy the response from your browser's Network tab, paste into ToolPry's JSON Formatter — it formats in milliseconds for typical API responses. For responses too large for a browser tool (10MB+), use curl https://api.example.com/endpoint | jq . in your terminal. jq streams large files without loading them entirely into memory and is significantly faster than browser-based tools for files over a few megabytes.