How to Format JSON: A Complete Guide
JSON (JavaScript Object Notation) is the most widely used data interchange format. But raw JSON is often minified, unindented, or difficult to read. This guide explains why formatting matters and how to do it effectively.
Why Format JSON?
Unformatted JSON is functionally correct but painful to work with. Consider this API response:
{"users":[{"id":1,"name":"Alice","email":"alice@example.com","roles":["admin","editor"]},{"id":2,"name":"Bob","email":"bob@example.com","roles":["viewer"]}]} Now compare it with formatted JSON:
{
"users": [
{
"id": 1,
"name": "Alice",
"email": "alice@example.com",
"roles": ["admin", "editor"]
},
{
"id": 2,
"name": "Bob",
"email": "bob@example.com",
"roles": ["viewer"]
}
]
} The second version reveals the structure immediately: an object containing a users array, each with an id, name, email, and roles array.
When to Format JSON
- Debugging API responses — See the structure clearly when troubleshooting.
- Code review — When sharing JSON examples in pull requests or documentation.
- Configuration files — Make config files readable for your team.
- Learning and teaching — Understand data relationships in nested structures.
- Logging — Formatted logs are easier to scan and search.
Indentation Styles
2 Spaces (Recommended)
The most popular choice. Used by Prettier, ESLint, and many major projects. Balances readability with compactness.
{
"name": "JSONCraft",
"version": "1.0"
} 4 Spaces
Provides more visual separation between levels. Common in languages with deeper nesting.
{
"name": "JSONCraft",
"version": "1.0"
} Tab Indentation
Uses tab characters instead of spaces. Less common for JSON but useful when your team or project requires it.
How to Format JSON Online
- Open the JSON Formatter.
- Paste your unformatted JSON into the input editor.
- Select your preferred indentation (2 spaces is the default).
- Click Format or press
Ctrl+Enter. - Copy or download the formatted result.
Formatting JSON in Code
Most programming languages have built-in JSON formatting:
JavaScript
JSON.stringify(data, null, 2); Python
import json
print(json.dumps(data, indent=2)) Bash (using jq)
cat data.json | jq '.' Common Mistakes
- Assuming minified JSON is broken — Minified JSON is valid; it just lacks whitespace for human readability.
- Adding comments — JSON does not support comments. Use a separate documentation file instead.
- Trailing commas — The last element in an array or object must not have a trailing comma.
- Single quotes — JSON strings must use double quotes. Single quotes cause parse errors.
Best Practices
- Use 2 spaces for consistency with most tools and formatters.
- Store configuration files in formatted JSON for readability.
- Minify JSON only for network transfer or storage optimization.
- Validate before formatting to catch syntax errors early.
- Use the JSON Validator to check validity before formatting.