JSON is everywhere — REST APIs, config files, database exports, WebSocket payloads. When something goes wrong with JSON, you need to format it, validate it, and find the error fast. Here's a complete guide to the tools and techniques.
Why JSON formatting matters
Raw API responses often look like this:
``
{"user":{"id":42,"name":"Alice","roles":["admin","editor"]},"meta":{"created":"2026-01-15","active":true,"score":9.8},"tags":["featured","verified"]}
`
Formatted:
<code>json
<p>{</p>
<p>"user": {</p>
<p>"id": 42,</p>
<p>"name": "Alice",</p>
<p>"roles": ["admin", "editor"]</p>
<p>},</p>
<p>"meta": {</p>
<p>"created": "2026-01-15",</p>
<p>"active": true,</p>
<p>"score": 9.8</p>
<p>},</p>
<p>"tags": ["featured", "verified"]</p>
<p>}</p>
</code>
Same data. The formatted version is readable; the minified version is not. For debugging API responses, config files, or any structured data, formatting is the first step.
The fastest way: browser-based formatter
For one-off tasks, a JSON formatter is the fastest approach — paste the JSON, click Format, and it's done. Good ones also validate the structure and show the exact line and character position of any error.
JSON formatting in Python
The json module:
`python
import json
Format a Python object
data = {"user": {"id": 42, "name": "Alice"}, "active": True}
print(json.dumps(data, indent=2))
Format from a JSON string
json_string = '{"user":{"id":42,"name":"Alice"}}'
parsed = json.loads(json_string)
print(json.dumps(parsed, indent=2))
Sort keys (useful for diff-ing)
print(json.dumps(data, indent=2, sort_keys=True))
Format a file
with open('data.json') as f:
data = json.load(f)
with open('data_formatted.json', 'w') as f:
json.dump(data, f, indent=2)
`
Command-line (no dependencies):
`bash
Format a file
python3 -m json.tool data.json
Format from pipe
curl -s https://api.example.com/users | python3 -m json.tool
Sort keys and indent with 4 spaces
python3 -m json.tool --indent 4 --sort-keys data.json
`
JSON formatting in JavaScript
`javascript
// Format an object
JSON.stringify(data, null, 2) // 2-space indent
JSON.stringify(data, null, 4) // 4-space indent
JSON.stringify(data, null, '\t') // tab indent
// Format from string
const formatted = JSON.stringify(JSON.parse(rawString), null, 2);
// Log formatted to console
console.log(JSON.stringify(data, null, 2));
`
Node.js command-line:
`bash
Format and validate a file
node -e "console.log(JSON.stringify(JSON.parse(require('fs').readFileSync('data.json', 'utf8')), null, 2))"
Or with jq (if installed)
jq '.' data.json
`
Using jq — the command-line JSON processor
jq is the standard tool for command-line JSON processing. It goes far beyond formatting:
`bash
Pretty-print
jq '.' data.json
Extract a field
jq '.user.name' data.json
Extract from an array
jq '.[0].name' data.json
jq '.[].name' data.json # all names
Filter array by condition
jq '.[] | select(.active == true)' data.json
Transform the structure
jq '{id: .id, fullName: .name}' data.json
Pipe API response directly
curl -s https://api.example.com/users | jq '.[].email'
Compact output (minify)
jq -c '.' data.json
Sort keys
jq --sort-keys '.' data.json
`
Common JSON validation errors
1. Trailing comma
<code>json
<p>// INVALID: JSON forbids trailing commas</p>
<p>{</p>
<p>"name": "Alice",</p>
<p>"active": true, ← trailing comma</p>
<p>}</p>
</code>
JavaScript objects allow trailing commas; JSON does not. This is the most common source of parse errors when pasting JavaScript object literals as JSON.
2. Single quotes
`json
// INVALID
{'name': 'Alice'}
// VALID
{"name": "Alice"}
`
JSON requires double quotes everywhere.
3. Unquoted keys
`json
// INVALID (valid JavaScript, invalid JSON)
{name: "Alice"}
// VALID
{"name": "Alice"}
`
4. Comments
<code>json
<p>// INVALID: JSON has no comment syntax</p>
<p>{</p>
<p>// This is the user ID</p>
<p>"id": 42</p>
<p>}</p>
</code>
JSON5 allows comments, but standard JSON does not. If your config file needs comments, use YAML or TOML instead, or strip comments before parsing.
5. Using NaN or Infinity
`json
// INVALID: not in JSON spec
{"score": NaN, "ratio": Infinity}
// Valid alternatives
{"score": null, "ratio": 999999}
`
JSON only supports null, not NaN, Infinity, or -Infinity.
Pretty-print settings: how much indentation?
- 2 spaces: Most common in JavaScript/Node.js projects (JSON.stringify(data, null, 2)
, Prettier default) - 4 spaces: Common in Python and Java projects; traditional
- Tabs: Some style guides (Go, some PHP projects)
For API responses served over HTTP, always minify (no whitespace). The indentation is for human reading only — minified JSON is smaller and faster to parse.
JSON Schema validation
If you need to validate not just JSON syntax but also the structure and types of the data, JSON Schema is the tool:
<code>json
<p>{</p>
<p>"$schema": "http://json-schema.org/draft-07/schema#",</p>
<p>"type": "object",</p>
<p>"required": ["name", "email"],</p>
<p>"properties": {</p>
<p>"name": {"type": "string", "minLength": 1},</p>
<p>"email": {"type": "string", "format": "email"},</p>
<p>"age": {"type": "integer", "minimum": 0}</p>
<p>}</p>
<p>}</p>
</code>
This schema validates that name and email are required strings, and age (if present) is a non-negative integer. In Node.js, use the ajv library to validate JSON against a schema programmatically.
Comparing two JSON responses
When you need to diff two API responses:
- Format both (consistent indentation)
- Sort keys (--sort-keys
in jq, sort_keys=True in Python) - Diff the results
`bash
jq approach
jq --sort-keys '.' response1.json > a.json
jq --sort-keys '.' response2.json > b.json
diff a.json b.json
Python approach
python3 -c "
import json, sys
a = json.load(open('response1.json'))
b = json.load(open('response2.json'))
print(json.dumps(a, indent=2, sort_keys=True))" > a.json
repeat for b.json
diff a.json b.json
`
For a visual diff without the terminal, format both JSONs and paste into a text diff checker.
JSON in databases
PostgreSQL: Native json and jsonb types. jsonb stores binary-parsed JSON and supports GIN indexing:
<code>sql
<p>SELECT data->>'name' FROM users WHERE data->>'active' = 'true';</p>
<p>SELECT * FROM users WHERE data @> '{"role": "admin"}';</p>
</code>
MySQL: JSON type with JSON functions:
<code>sql
<p>SELECT JSON_EXTRACT(data, '$.name') FROM users;</p>
<p>SELECT * FROM users WHERE JSON_CONTAINS(data, '"admin"', '$.roles');</p>
</code>
MongoDB: Stores documents natively as BSON (binary JSON):
<code>javascript
<p>db.users.find({ "role": "admin", "active": true })</p>
</code>
JSON formatting is a small thing that saves significant time when debugging API responses and data pipelines. Having the right tool for your context — a browser formatter for one-offs, jq for the command line, the json` module for scripts — makes the process frictionless.
Originally published at https://snappytools.app/json-formatter/