JSON formatting is one of those things you do ten times a day but rarely think about. Here's everything you need to know.
JSON.stringify: The Basics
const data = { name: "Alice", roles: ["admin", "editor"] };
// Minified (default)
JSON.stringify(data)
// '{"name":"Alice","roles":["admin","editor"]}'
// Pretty-printed (2-space indent)
JSON.stringify(data, null, 2)
// {
// "name": "Alice",
// "roles": [
// "admin",
// "editor"
// ]
// }
// Tab indent
JSON.stringify(data, null, '\t')
The Replacer Function (Secret Power)
// Filter sensitive fields
JSON.stringify(data, (key, value) => {
if (key === 'password' || key === 'token') return undefined;
return value;
}, 2);
// Or pick specific keys
JSON.stringify(data, ['name', 'email'], 2);
Command Line: jq
jq is the JSON Swiss Army knife:
# Pretty-print
cat data.json | jq '.'
# Minify
cat data.json | jq -c '.'
# Sort keys
cat data.json | jq -S '.'
# Extract fields
cat data.json | jq '.users[] | {name, email}'
Python
import json
# Pretty-print
json.dumps(data, indent=2, ensure_ascii=False)
# Sort keys (great for diffs)
json.dumps(data, indent=2, sort_keys=True)
# Minify
json.dumps(data, separators=(',', ':'))
# From command line
python3 -m json.tool input.json
JSON Validation Checklist
Common errors that break JSON:
- Trailing commas:
{"a": 1,}— INVALID - Single quotes:
{'a': 1}— INVALID - Comments:
{"a": 1 // note}— INVALID - Unquoted keys:
{a: 1}— INVALID - NaN/Infinity: not valid JSON values
JSON5 and JSONC
If you need comments and trailing commas, use JSON5:
// json5 - JavaScript
import JSON5 from 'json5';
const data = JSON5.parse(`{
// This is a comment
name: 'Alice',
age: 30,
}`);
VS Code uses JSONC (JSON with Comments) for tsconfig.json and settings.json.
CI/CD Integration
# GitHub Actions - validate all JSON files
- name: Lint JSON
run: |
find . -name "*.json" -not -path "*/node_modules/*" \
-exec sh -c 'python3 -m json.tool "$1" > /dev/null || echo "Invalid: $1"' _ {} \;
Large File Performance
| Parser | Speed (1GB JSON) | Memory |
|---|---|---|
| simdjson | ~2s | Low |
| jq --stream | ~10s | Constant |
| Python ijson | ~30s | Constant |
| JSON.parse() | ~5s | Very high |
For files over 100MB, use streaming parsers.
Try It Online
Format, validate, minify, and explore JSON with DevToolBox's JSON Formatter — syntax highlighting, error detection, tree view, copy with one click.
What's your go-to JSON formatting tool? Share below!
Top comments (0)