How to Format JSON: The Complete Developer Guide (2026)
Raw JSON from an API response looks like this: {"user":{"id":42,"name":"Maria","roles":["admin","editor"],"active":true}}. One long line, no whitespace, hard to read at a glance. Formatting it (also called pretty-printing or beautifying) adds indentation and line breaks so the structure is clear at once. This guide covers JSON formatting end to end: how to do it online, how to do it in code, what to watch out for, and why it matters beyond readability.
What is JSON Formatting?
JSON formatting turns minified or compact JSON into an indented, human-readable layout. The data itself does not change; only whitespace is added. A formatter puts a newline after every property, indents nested objects and arrays, and aligns keys so the hierarchy of the data is easy to see.
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 option is ToolPry's JSON Formatter. Paste your JSON and it formats and validates in real time, with no button to click. It runs entirely in your browser, so your data never leaves your machine. There is no sign-up, no file size limit, and no usage cap.
For API responses, 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 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 work with JSON files or API responses on the command line, these tools format JSON without a browser.
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 go-to JSON tool 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.
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
The two are related but different. Formatting arranges valid JSON into a readable layout. Validation checks whether the JSON is syntactically correct: 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 refuses to format it and shows the exact location of the problem. That makes formatting a useful debugging step, because a rejected input tells you straight away where the error is.
Common validation errors: 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). A validator catches all of these immediately.
When to Minify vs When to Format
Format JSON when you are debugging, reading API responses, writing documentation, reviewing a 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 network payload size matters. Removing whitespace can cut JSON size by 20–40%, depending on the data. For high-traffic APIs handling thousands of requests per second, that adds up to real bandwidth and infrastructure savings.
A good workflow is to develop and debug with formatted JSON and serve minified JSON in production. Most HTTP frameworks have middleware or serializer options that control this. Express.js has app.set('json spaces', 2) for development, and most production setups leave it unset so output defaults to minified.
JSON Formatting Best Practices
Consistent indentation: Pick 2 or 4 spaces and use 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. That ends formatting debates in code review and keeps JSON files consistent across the team.
Validate before deployment: Never deploy a configuration file without validating it. A syntax error in a JSON config file can crash your whole 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: For deeply nested JSON (5+ levels), a tree view is often more useful than indented text. ToolPry's formatter has a tree view mode that lets you collapse and expand individual nodes, so you can move around large API responses without getting lost in the indentation.
Quick tip: In VS Code, 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+), and the page may freeze while the data is processed. For large files, use a command-line tool. jq can process gigabyte-sized JSON files efficiently because it streams the data rather than loading all of it into memory.
If you only need part of a large JSON file, jq lets you filter to 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 generated by databases or log aggregators, ask 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, and knowing the 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 instead of trying 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. You can also 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 block, select it visually, then run :!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.