How to Format JSON: Methods, Tools & Best Practices
Learn every way to format JSON — from online tools and CLI commands to programmatic approaches. Compare indentation styles and set up auto-formatting in your editor.
Why Formatting JSON Matters
Unformatted JSON is technically valid, but it's hostile to humans. A single-line blob of nested objects and arrays is nearly impossible to scan during a debugging session, and it turns code reviews into guessing games.
Properly formatted JSON gives you three immediate benefits:readability — you can visually trace the hierarchy of keys and values; debuggability — diff tools and error messages reference line numbers that actually mean something; and collaboration — teammates reviewing your API response fixtures or config files can understand them at a glance.
Formatting also prevents subtle bugs. When JSON is minified, it's easy to miss a misplaced bracket or a duplicated key. Expanding the structure makes those issues jump out.
The Rules of JSON Formatting
Before reaching for a tool, it helps to understand what "formatted JSON" actually means. The JSON spec (RFC 8259) doesn't mandate any whitespace rules — formatting is purely a presentation concern. That said, the community has settled on clear conventions:
- Each key-value pair sits on its own line.
- Nested objects and arrays are indented one level deeper than their parent.
- A colon follows the key, separated by a single space:
"key": "value". - Commas appear at the end of each line (not the beginning).
- Opening braces and brackets stay on the same line as the key; closing ones align with the parent indentation level.
Here's a minimal example. This minified JSON:
{"name":"Alice","age":30,"roles":["admin","editor"],"address":{"city":"Portland","state":"OR"}}Becomes this when formatted with 2-space indentation:
{
"name": "Alice",
"age": 30,
"roles": [
"admin",
"editor"
],
"address": {
"city": "Portland",
"state": "OR"
}
}The 3 Ways to Format JSON
Every approach falls into one of three buckets: online tools, command-line utilities, or programmatic formatting inside your application code. The right choice depends on where you are in your workflow and how often you need to do it.
1. Online Tools
Browser-based formatters are the fastest path when you just need to pretty-print a one-off payload — paste it in, click a button, copy the result. There's nothing to install and no context-switching to a terminal.
Online tools work well for quick debugging, sharing formatted snippets with non-technical stakeholders, or when you're on a machine where you can't install software. The downside is that they don't integrate into automated pipelines.
Try it yourself: Paste any JSON into our JSON Formatter to instantly beautify it with your choice of indentation.
2. Command-Line Tools
If you live in the terminal, two commands cover almost every formatting need:
Python's built-in json.tool module — available on any machine with Python installed, no extra packages required:
echo '{"name":"Alice","age":30}' | python -m json.toolThis outputs nicely indented JSON to stdout. You can pipe a file through it just as easily:
python -m json.tool data.json > data-formatted.jsonjq — a lightweight, purpose-built JSON processor. The simplest formatting command is just the identity filter:
cat data.json | jq '.'jqalso adds syntax highlighting in most terminals, and you can chain filters to transform and format in one pass. It's the go-to choice for shell scripts that process JSON.
Both commands can be chained into CI pipelines. For example, you might run jq --sort-keys . in a pre-commit hook to ensure all JSON config files in a repo are consistently formatted.
3. Programmatic Formatting
When you're writing application code, formatting JSON is a one-liner in most languages.
JavaScript / TypeScript:
const formatted = JSON.stringify(data, null, 2);The third argument to JSON.stringify controls indentation. Pass 2 for 2 spaces, 4 for 4 spaces, or "\\t" for tabs.
Python:
import json
formatted = json.dumps(data, indent=2, ensure_ascii=False)Go:
formatted, err := json.MarshalIndent(data, "", " ")Programmatic formatting is essential when you generate JSON as part of your application — writing config files, creating API response fixtures, or generating documentation. You control the output completely.
Comparing Formatting Approaches
Here's a quick reference to help you pick the right method for the situation:
| Criteria | Online Tool | CLI (jq / json.tool) | Programmatic |
|---|---|---|---|
| Ease of use | Paste and click | One-line command | Requires code context |
| Speed for one-off tasks | Fastest | Fast | Slower (need a script) |
| Automation / CI | Not suitable | Excellent | Excellent |
| Customization | Limited | Moderate (flags) | Full control |
| Works offline | No | Yes | Yes |
| Handles large files | Browser limits | Streams well | Depends on implementation |
The Indentation Debate: 2 Spaces vs 4 Spaces vs Tabs
This is one of those debates that generates more heat than light, but there are practical reasons to prefer each option.
2 Spaces
The most common choice in JSON. It keeps deeply nested structures compact while still providing clear visual hierarchy. Most JavaScript ecosystem tools (ESLint, Prettier, npm's package.json) default to 2 spaces. If you're working with web APIs or Node.js projects, this is the safe default.
4 Spaces
Popular in Python-adjacent workflows and some enterprise Java shops. The extra width makes nesting levels more obvious, which can help when reading large configuration files. The tradeoff is that deeply nested JSON pushes quickly toward the right edge of the screen.
Tabs
Tabs let each developer set their own visual width in their editor. This sounds ideal in theory, but in practice most JSON tools and linters expect spaces. Tabs also render inconsistently in web-based diff viewers and GitHub PRs.
When to use each:
- 2 spaces — web projects, JavaScript/TypeScript codebases, API payloads. The community standard.
- 4 spaces — Python-heavy teams, large config files where clarity wins over compactness.
- Tabs — monorepos with mixed language preferences and strict accessibility requirements (tabs allow user-configured widths).
The most important thing is consistency within a project. Pick one and enforce it.
Sorting Keys
Most formatters offer a "sort keys" option that alphabetizes object keys. This isn't just cosmetic — it has real benefits for version control.
When keys are sorted, diffs become meaningful. Without sorting, two developers might add the same keys in different orders, producing noisy diffs that obscure the actual change. Sorted keys eliminate this entirely.
Sorted keys also make it easier to scan large config files. If you know the key you're looking for, you can jump to its alphabetical position without searching.
The one caveat: some JSON files have intentional key ordering (like a package.json where name and version come first by convention). In those cases, preserve the original order.
In jq, sort keys with:
jq --sort-keys '.' data.jsonIn JavaScript, pass a replacer function or use a library like json-stable-stringify for deterministic key order.
Auto-Format on Save in VS Code
The best formatting is the kind you never think about. VS Code can automatically format JSON files every time you save. Here's how to set it up:
Step 1: Open your settings (Cmd+, on macOS, Ctrl+, on Windows/Linux) and add these entries:
{
"editor.formatOnSave": true,
"[json]": {
"editor.defaultFormatter": "esbenp.prettier-vscode",
"editor.tabSize": 2
},
"[jsonc]": {
"editor.defaultFormatter": "esbenp.prettier-vscode",
"editor.tabSize": 2
}
}Step 2: Install the Prettier - Code formatterextension if you haven't already. It handles JSON formatting along with every other language in your project.
Step 3: Create a .prettierrc at your project root to standardize settings across the team:
{
"tabWidth": 2,
"useTabs": false
}Now every JSON file in the project gets formatted identically, regardless of who edited it. No more formatting-only diffs in pull requests.
Handling Edge Cases
Most formatting tools handle standard JSON without issue, but a few situations can trip you up:
- Large numbers— JSON doesn't distinguish between integers and floats. Some formatters may reformat
1.0as1or lose precision on very large integers. If precision matters, verify the output. - Unicode escapes — A formatter might convert
\u00e9to the literal characteréor vice versa. Both are valid JSON, but the change can cause unexpected diffs. - Empty objects and arrays — Some formatters expand
{}to multiple lines. Others keep them compact. This is a style preference, but be aware it can vary between tools. - Trailing newline — POSIX convention says text files should end with a newline. Most formatters add one, but not all. Check your
.editorconfigif this matters for your CI.
Formatting as Part of Your Workflow
The most effective teams treat JSON formatting the same way they treat code formatting — as an automated, non-negotiable part of the development process.
Pre-commit hooks: Use a tool like husky with lint-staged to run Prettier or jq on JSON files before every commit. This catches formatting issues before they enter the codebase.
CI checks:Add a formatting check to your CI pipeline that fails if any JSON files aren't properly formatted. Prettier has a --check flag for exactly this purpose.
Editor integration: Format on save eliminates manual formatting entirely. Combined with a shared config file, it ensures every team member produces identical output.
The goal is to make formatting invisible — something that happens automatically, so developers can focus on the actual content of their JSON files rather than how they look.
Try it yourself: Paste unformatted JSON into our JSON Formatter to instantly beautify it. You can also validate your JSON to catch structural errors before formatting.