JSON (JavaScript Object Notation) is the lingua franca of modern web development. APIs speak it, configuration files use it, and databases store it. But anyone who's stared at a wall of minified JSON knows the pain: without proper formatting, JSON is nearly impossible to read, debug, or edit.
This guide covers everything you need to know about formatting JSON — from basic syntax rules to advanced validation techniques. And when you need a quick format, our free JSON Formatter runs entirely in your browser with zero data leaving your device.
Why JSON Formatting Matters
Minified JSON saves bytes on the wire, but it's terrible for humans. Consider this API response:
{"users":[{"id":1,"name":"Alice","email":"alice@example.com","roles":["admin","editor"],"settings":{"theme":"dark","notifications":true}},{"id":2,"name":"Bob","email":"bob@example.com","roles":["viewer"],"settings":{"theme":"light","notifications":false}}]}Now the same data, pretty-printed:
{
"users": [
{
"id": 1,
"name": "Alice",
"email": "alice@example.com",
"roles": ["admin", "editor"],
"settings": {
"theme": "dark",
"notifications": true
}
},
{
"id": 2,
"name": "Bob",
"email": "bob@example.com",
"roles": ["viewer"],
"settings": {
"theme": "light",
"notifications": false
}
}
]
}The difference is night and day. Formatted JSON lets you spot missing fields, incorrect nesting, and type errors at a glance.
JSON Syntax Rules: The Essentials
Before formatting, you need valid JSON. Here are the rules that trip people up:
1. Keys Must Be Double-Quoted Strings
// ❌ Invalid — single quotes
{'name': 'Alice'}
// ❌ Invalid — unquoted keys
{name: "Alice"}
// ✅ Valid
{"name": "Alice"}2. No Trailing Commas
// ❌ Invalid — trailing comma after last item
{
"name": "Alice",
"age": 30,
}
// ✅ Valid
{
"name": "Alice",
"age": 30
}3. No Comments
Standard JSON does not support comments. This is one of the most common frustrations and a reason why formats like JSONC and JSON5 exist. If you need comments in config files, consider using YAML or TOML instead.
4. Strings Must Use Double Quotes
// ❌ Invalid
{"name": 'Alice'}
// ✅ Valid
{"name": "Alice"}5. Supported Data Types
JSON supports exactly six data types:
- String:
"hello" - Number:
42,3.14,-1,1e10 - Boolean:
true,false - Null:
null - Array:
[1, 2, 3] - Object:
{"key": "value"}
No undefined, no NaN, no Infinity, no dates, no functions. If you're serializing JavaScript objects, watch out for these.
How to Format JSON Programmatically
JavaScript
// Pretty-print with 2-space indentation
const formatted = JSON.stringify(data, null, 2);
// With custom indentation (tab)
const tabbed = JSON.stringify(data, null, "\t");
// Minify (remove all whitespace)
const minified = JSON.stringify(data);Python
import json
# Pretty-print
formatted = json.dumps(data, indent=2, ensure_ascii=False)
# Sort keys alphabetically
sorted_json = json.dumps(data, indent=2, sort_keys=True)
# Minify
minified = json.dumps(data, separators=(",", ":"))Command Line with jq
# Pretty-print a file
cat data.json | jq .
# Pretty-print an API response
curl -s https://api.example.com/users | jq .
# Minify
jq -c . < data.json
# Extract a specific field
cat data.json | jq '.users[0].name'
# Sort keys
jq -S . < data.jsonCommon JSON Errors and How to Fix Them
Unexpected Token
This usually means there's a syntax error — a missing comma, extra bracket, or invalid character. The error message often includes a position number, which tells you exactly where the parser choked.
Unexpected End of JSON Input
Your JSON is incomplete — likely a missing closing bracket } or ]. Count your opening and closing brackets to find the mismatch.
Invalid Unicode Escape
JSON requires that special characters in strings are properly escaped. Backslashes must be doubled (\\), and control characters need unicode escapes like \u000A.
JSON Formatting Best Practices
- Use 2-space indentation — it's the most common convention and balances readability with compactness.
- Sort keys in configs — alphabetical key ordering makes it easier to find settings and produces cleaner diffs.
- Validate before deploying — a single syntax error in a JSON config file can crash your application. Always validate.
- Use a formatter in your editor — Prettier, ESLint, or VS Code's built-in formatter can auto-format JSON on save.
- Consider JSON Schema — for complex configs, JSON Schema validates structure and types, not just syntax.
JSON vs Other Data Formats
When should you use JSON, and when should you reach for alternatives?
- YAML: Better for human-written configs (supports comments, anchors, multiline strings). Worse for machine-to-machine communication.
- TOML: Great for simple, flat configs. Less suited for deeply nested structures.
- Protocol Buffers / MessagePack: Binary formats that are smaller and faster to parse. Best for high-performance internal services.
- CSV: Better for tabular data. JSON is better for nested structures.
Format JSON Instantly with DevToolbox
Our JSON Formatter gives you instant pretty-printing, validation, and minification. Paste your JSON, and the tool highlights syntax errors with line numbers. You can switch between different indentation styles and copy the result with one click.
Everything runs 100% in your browser — no server, no cookies, no data collection. This means you can safely format sensitive data like API keys, user records, or internal configurations without worrying about exposure.
Working with related formats? Try the YAML ↔ JSON Converter or the SQL Formatter for database queries.
Summary
JSON formatting isn't glamorous, but it's essential. Clean, validated JSON prevents bugs, speeds up debugging, and makes collaboration easier. Remember: always double-quote your keys, never use trailing commas, and validate before deploying.
For quick conversions, DevToolbox's JSON Formatter is always a click away — free, private, and instant.