Raw JSON from an API or log file is often a single unbroken line — valid, but impossible to read at a glance. Formatting JSON (also called "pretty-printing" or "beautifying") adds consistent indentation and line breaks so the structure becomes immediately clear. This guide shows you how to format a JSON file or string in JavaScript, Python, the command line, and directly in your browser.
What Does "Formatting JSON" Mean?
A JSON formatter takes a compact or inconsistently indented JSON string and rewrites it with:
- Each key–value pair on its own line
- Nested objects and arrays indented by a fixed number of spaces (usually 2 or 4)
- No trailing whitespace
// Before formatting (minified)
{"user":{"name":"Alice","age":30,"roles":["admin","editor"]}}
// After formatting (2-space indent)
{
"user": {
"name": "Alice",
"age": 30,
"roles": [
"admin",
"editor"
]
}
}The two forms are semantically identical — any JSON parser produces the same data structure from either. Formatting is purely for human readability.
How to Format JSON in JavaScript
JSON.stringify() accepts a second argument (a replacer) and a third argument (the indent level). Pass null for the replacer and 2 for 2-space indentation (for the full API, see How to Stringify JSON):
const obj = { user: { name: "Alice", age: 30, roles: ["admin", "editor"] } };
// Compact (no formatting)
JSON.stringify(obj);
// '{"user":{"name":"Alice","age":30,"roles":["admin","editor"]}}'
// Pretty-printed with 2-space indent
JSON.stringify(obj, null, 2);
// {
// "user": {
// "name": "Alice",
// "age": 30,
// "roles": [
// "admin",
// "editor"
// ]
// }
// }
// 4-space indent
JSON.stringify(obj, null, 4);
// Tab-indented
JSON.stringify(obj, null, '\t');Format a JSON string (not an object)
If you have a JSON string that's already valid but poorly formatted, parse it first, then re-stringify:
const raw = '{"name":"Alice","age":30}';
const formatted = JSON.stringify(JSON.parse(raw), null, 2);
console.log(formatted);Sort keys alphabetically
To sort object keys during formatting, pass a replacer function that sorts the keys of every object encountered:
function sortedStringify(obj, indent = 2) {
return JSON.stringify(obj, (key, value) => {
if (value && typeof value === 'object' && !Array.isArray(value)) {
return Object.keys(value).sort().reduce((acc, k) => {
acc[k] = value[k];
return acc;
}, {});
}
return value;
}, indent);
}How to Format JSON in Python
Python's built-in json module handles formatting via the indent parameter:
import json
# Format a Python dict
data = {"user": {"name": "Alice", "age": 30, "roles": ["admin", "editor"]}}
formatted = json.dumps(data, indent=2)
print(formatted)
# Format a JSON string
raw = '{"name":"Alice","age":30}'
formatted = json.dumps(json.loads(raw), indent=2)
# Sort keys alphabetically
formatted = json.dumps(data, indent=2, sort_keys=True)
# Format a JSON file
with open('input.json') as f:
data = json.load(f)
with open('output.json', 'w') as f:
json.dump(data, f, indent=2)How to Format a JSON File on the Command Line
Using jq (recommended)
jq is the standard command-line JSON processor. It formats JSON by default:
# Pretty-print a JSON file
jq . input.json
# Pretty-print and save to a new file
jq . input.json > output.json
# Format JSON from a curl response
curl -s https://api.example.com/users | jq .
# Sort keys
jq --sort-keys . input.jsonUsing Python (no install required)
Python's json.tool module works as a command-line formatter on any system with Python installed:
# Format a file
python3 -m json.tool input.json
# Format from stdin
echo '{"name":"Alice","age":30}' | python3 -m json.tool
# Sort keys
python3 -m json.tool --sort-keys input.jsonUsing Node.js
node -e "const fs=require('fs'); const d=JSON.parse(fs.readFileSync('input.json')); console.log(JSON.stringify(d,null,2))"How to Convert Data to JSON Format
"Format to JSON" often means serialising data from another format — a Python dict, a CSV file, a YAML config — into valid JSON.
From YAML to JSON
# Python
import yaml, json
with open('config.yaml') as f:
data = yaml.safe_load(f)
print(json.dumps(data, indent=2))Or use the YAML to JSON converter in your browser — no code required. For when to choose each format, see JSON vs YAML; for background on why YAML 1.2 is a proper superset of JSON, see YAML 1.2 and JSON Compatibility.
From CSV to JSON
import csv, json
with open('data.csv') as f:
rows = list(csv.DictReader(f))
print(json.dumps(rows, indent=2))From a JavaScript object
JavaScript objects look like JSON but aren't — they can have unquoted keys, single-quoted strings, trailing commas, and comments. Paste an invalid JavaScript object literal into JSON Fix to convert it to valid JSON automatically.
Format JSON in Your Editor (Prettier, VS Code, pre-commit)
For everyday work, the most useful place to format JSON is on save — so it never lands in git or a PR unformatted.
Prettier
# install
npm i -D prettier
# format every .json (and source) file in-place
npx prettier --write "**/*.{json,jsonc}"
# check only (CI-friendly, exits non-zero if anything needs formatting)
npx prettier --check "**/*.json" Prettier handles JSON and JSONC out of the box. A two-line .prettierrc like { "tabWidth": 2 } is usually all you need.
VS Code — Format on Save
Install the Prettier extension and add to your workspace settings.json:
{
"editor.formatOnSave": true,
"[json]": { "editor.defaultFormatter": "esbenp.prettier-vscode" },
"[jsonc]": { "editor.defaultFormatter": "esbenp.prettier-vscode" }
}Pre-commit hook
To prevent unformatted JSON from being committed at all, wire up lint-staged + husky:
// package.json
{
"lint-staged": { "*.{json,jsonc}": "prettier --write" }
}
# install the hook
npx husky add .husky/pre-commit "npx lint-staged"JSON Format Example: Before and After
// Unformatted — valid but unreadable
{"orders":[{"id":1001,"customer":{"name":"Alice","email":"alice@example.com"},"items":[{"sku":"A1","qty":2,"price":9.99},{"sku":"B3","qty":1,"price":24.99}],"status":"shipped"},{"id":1002,"customer":{"name":"Bob","email":"bob@example.com"},"items":[{"sku":"C7","qty":3,"price":4.49}],"status":"pending"}]}
// Formatted — same data, now readable
{
"orders": [
{
"id": 1001,
"customer": {
"name": "Alice",
"email": "alice@example.com"
},
"items": [
{ "sku": "A1", "qty": 2, "price": 9.99 },
{ "sku": "B3", "qty": 1, "price": 24.99 }
],
"status": "shipped"
},
{
"id": 1002,
"customer": {
"name": "Bob",
"email": "bob@example.com"
},
"items": [
{ "sku": "C7", "qty": 3, "price": 4.49 }
],
"status": "pending"
}
]
}Frequently Asked Questions
How do I format JSON in JavaScript?
Use JSON.stringify(value, null, 2) — the third argument sets the indentation (2 spaces, 4 spaces, or '\t' for tabs). To format an existing JSON string, parse it first: JSON.stringify(JSON.parse(raw), null, 2).
How do I pretty-print JSON on the command line?
Use jq . file.json (formats by default), or python3 -m json.tool file.json if jq isn't installed. Add --sort-keys / --sort-keys to order keys alphabetically.
What's the difference between formatting and minifying JSON?
Formatting adds whitespace for readability; minifying removes it to shrink file size. They are exact opposites and both preserve the data. See How to Minify JSON for the reverse operation.
Does formatting JSON change the data?
No. Indentation and line breaks are insignificant whitespace in JSON — every parser produces the identical data structure from compact or pretty-printed input.
Format JSON Online — No Setup
If you just need to format a JSON string right now without writing any code, JSON Fix formats your JSON instantly. Paste the JSON, click Format, and copy the result. It also repairs common errors (trailing commas, single quotes, unquoted keys) before formatting, so it works even if your JSON isn't quite valid yet.
- JSON Fix — format and repair JSON in one step
- How to Minify JSON — the reverse operation, and when it's worth doing
- How to Convert CSV and XML to JSON — turn other formats into JSON
- jq Tutorial — format and transform JSON on the command line
- JSON Diff — compare formatted and original JSON side by side
- What Is JSON? — the six data types and the rules that make JSON strict
- JSON Format Examples — copy-pasteable examples for every data type and real-world pattern
- YAML to JSON — convert YAML to formatted JSON