How to Pretty Print JSON: Online Tools and Code
Last updated:
Pretty printing JSON means adding whitespace — newlines and indentation — so the structure is easy to read. A blob like {"name":"Alice","age":30,"hobbies":["reading","coding"]} becomes a properly nested, line-by-line document. Every language has a built-in way to do it, and there are also great command-line tools and online formatters.
Pretty Print in JavaScript (JSON.stringify)
The built-in JSON.stringify function accepts a third argument that controls indentation. Pass a number for spaces or a string for a custom indent character.
const data = {
name: "Alice",
age: 30,
hobbies: ["reading", "coding"],
address: {
city: "London",
country: "GB"
}
}
// 2-space indent (most common)
console.log(JSON.stringify(data, null, 2))
// Output:
// {
// "name": "Alice",
// "age": 30,
// "hobbies": [
// "reading",
// "coding"
// ],
// "address": {
// "city": "London",
// "country": "GB"
// }
// }The three arguments are: value (the data to serialize), replacer (pass null to include all properties), and space (the indent).
// 4-space indent
JSON.stringify(data, null, 4)
// Tab indent
JSON.stringify(data, null, ' ')
// Minified (no indent — default)
JSON.stringify(data)
// With a replacer array — only include specific keys
JSON.stringify(data, ['name', 'age'], 2)
// Output:
// {
// "name": "Alice",
// "age": 30
// }
// Pretty print to console (quick debugging)
console.log(JSON.stringify(data, null, 2))
// Write pretty JSON to a file in Node.js
import { writeFileSync } from 'fs'
writeFileSync('output.json', JSON.stringify(data, null, 2))Handling Special Values
JSON.stringify silently drops undefined, functions, and Symbol properties. Inside arrays, they become null.
const tricky = {
name: "Alice",
age: undefined, // dropped from output
greet: () => "hello", // dropped from output
scores: [10, undefined, 30] // undefined -> null
}
JSON.stringify(tricky, null, 2)
// {
// "name": "Alice",
// "scores": [10, null, 30]
// }Pretty Print in Python (json.dumps)
Python's built-in json module provides json.dumps for strings and json.dump for writing to files. The indent parameter controls pretty printing.
import json
data = {
"name": "Alice",
"age": 30,
"hobbies": ["reading", "coding"],
"address": {"city": "London", "country": "GB"}
}
# Pretty print to string (4-space indent — Python convention)
pretty = json.dumps(data, indent=4)
print(pretty)
# Pretty print with sorted keys
print(json.dumps(data, indent=4, sort_keys=True))
# Tab indentation
print(json.dumps(data, indent=" "))
# Write pretty JSON to a file
with open("output.json", "w") as f:
json.dump(data, f, indent=4)
# Load from file and re-pretty-print
with open("input.json") as f:
loaded = json.load(f)
print(json.dumps(loaded, indent=4))For non-ASCII characters (e.g., Chinese, Arabic), json.dumps escapes them by default to \uXXXX. Pass ensure_ascii=False to keep them as-is:
data = {"city": "北京"}
print(json.dumps(data, indent=2, ensure_ascii=False))
# {
# "city": "北京"
# }
# Without ensure_ascii=False:
# {
# "city": "\u5317\u4eac"
# }Command Line: jq and python -m json.tool
Two reliable command-line options for pretty printing JSON — one needs no installation if Python is present, the other adds color and much more power.
python -m json.tool
# Pretty print a file (4-space indent by default)
python -m json.tool input.json
# Custom indent
python -m json.tool --indent 2 input.json
# From stdin (pipe)
cat input.json | python -m json.tool
# From curl output
curl -s https://api.example.com/data | python -m json.tool
# Write to file
python -m json.tool input.json > pretty.json
# Sort keys
python -m json.tool --sort-keys input.jsonjq
jq is a dedicated JSON processor. The . identity filter simply passes the input through while applying pretty formatting with colors.
# Install
brew install jq # macOS
sudo apt install jq # Debian/Ubuntu
winget install jqlang.jq # Windows
# Pretty print a file
jq '.' input.json
# From stdin / curl
curl -s https://api.example.com/data | jq '.'
# Tab indentation
jq --tab '.' input.json
# Compact (minified) output
jq -c '.' input.json
# Disable color (for piping to less, etc.)
jq -M '.' input.json | less
# Write to file
jq '.' input.json > pretty.jsonUnlike python -m json.tool, jq also lets you filter and transform while pretty printing:
# Pretty print and select a nested key
jq '.data.users' input.json
# Pretty print an array of names
jq '[.users[].name]' input.json
# Pretty print and filter by field value
jq '.users[] | select(.active == true)' input.jsonPretty Print in VS Code
VS Code can format JSON files in one keystroke using its built-in formatter or the Prettier extension.
- Keyboard shortcut: Shift+Alt+F on Windows/Linux, Shift+Option+F on Mac
- Right-click menu: Right-click anywhere in the editor → "Format Document"
- Command Palette: Ctrl+Shift+P / Cmd+Shift+P, then type "Format Document"
- Format on save: Add
"editor.formatOnSave": trueto your VS Code settings for automatic formatting
// .vscode/settings.json — format JSON on save
{
"editor.formatOnSave": true,
"[json]": {
"editor.defaultFormatter": "esbenp.prettier-vscode",
"editor.tabSize": 2
},
"[jsonc]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
}
}If a file isn't recognized as JSON, open the Command Palette and select "Change Language Mode", then choose JSON before formatting.
Online JSON Formatters
Online formatters are the fastest option when you have JSON in your clipboard and don't want to open a terminal. They also validate JSON and show syntax errors.
- Jsonic Formatter — processes entirely in your browser (no server upload), supports syntax highlighting and minify toggle
- jsonformatter.org — long-standing formatter with tree view
- jsonlint.com — focuses on validation with line-by-line error reporting
For sensitive data (API keys, personal data), use a formatter that processes client-side. The Jsonic formatter never sends your JSON to a server.
Pretty Print with Custom Indent
The indent can be any number of spaces (1–10) or a custom string. Here's how each language handles custom indent:
// JavaScript — number of spaces
JSON.stringify(data, null, 2) // 2 spaces (most common)
JSON.stringify(data, null, 4) // 4 spaces
JSON.stringify(data, null, ' ') // tab
// Python — number of spaces or string
json.dumps(data, indent=2)
json.dumps(data, indent=4) // Python convention
json.dumps(data, indent=" ")
// jq
jq '.' input.json // 2-space default
jq --tab '.' input.json // tab
jq --indent 4 '.' input.json // 4 spaces
// python -m json.tool
python -m json.tool --indent 2 input.json
python -m json.tool --indent 4 input.jsonThe JSON specification does not mandate any particular indent style — the choice is purely aesthetic. Two spaces is the most common convention in JavaScript/Node.js projects. Four spaces is the Python convention. Tabs are used when consistency with the surrounding codebase matters more than character count.
Minify vs Pretty Print
Pretty printing and minifying are opposite operations. Both produce valid JSON — the difference is purely whitespace.
| Method | Indent Size | Color Support | Streaming Support | Language / Tool |
|---|---|---|---|---|
JSON.stringify(d, null, 2) | Any (number or string) | No | No | JavaScript / Node.js |
json.dumps(d, indent=4) | Any (int or string) | No | No | Python |
jq '.' | 2 (default), tab, or custom | Yes | Yes (line-delimited) | CLI (any language) |
python -m json.tool | 4 (default) or custom | No | No | CLI (Python built-in) |
| VS Code Format Document | Configured in settings | Yes (editor highlighting) | No | Editor |
| Jsonic Online Formatter | 2 or 4 (selectable) | Yes | No | Browser (client-side) |
// Minified — compact, no whitespace
{"name":"Alice","age":30,"hobbies":["reading","coding"]}
// Pretty printed with 2 spaces — human-readable
{
"name": "Alice",
"age": 30,
"hobbies": [
"reading",
"coding"
]
}
// JavaScript: minify
JSON.stringify(data) // no third argument = minified
// JavaScript: pretty print
JSON.stringify(data, null, 2) // third argument = pretty
// Python: minify (remove all whitespace)
json.dumps(data, separators=(',', ':'))
// Python: pretty print
json.dumps(data, indent=4)Use minified JSON for HTTP API responses, stored data, and any scenario where bandwidth or storage matters. Use pretty-printed JSON for config files, debug logs, version-controlled data files, and any JSON a human reads regularly.
Definitions
- Pretty printing
- The process of adding whitespace — newlines, indentation, and spaces after separators — to a JSON string to make it human-readable. The resulting JSON is semantically identical to the minified form; only formatting changes.
- Indent
- The whitespace prepended to each line of output based on nesting depth. Common choices are 2 spaces (JavaScript projects), 4 spaces (Python), or a tab character. JSON.stringify accepts any string as the indent argument.
- Minification
- The opposite of pretty printing — removing all unnecessary whitespace to produce the most compact valid JSON string. Useful for reducing payload size in HTTP responses and stored data. In Python:
json.dumps(data, separators=(',', ':')). - jq
- A lightweight command-line JSON processor. The
.(identity) filter pretty prints with color by default. jq also supports filtering, transformation, and streaming of large JSON files — far beyond whatpython -m json.tooloffers. - JSON formatter
- Any tool — online, CLI, or library — that takes raw JSON and outputs a pretty-printed version, typically with syntax highlighting. Online formatters also validate JSON and report parse errors with line numbers.
FAQ
How do I pretty print JSON in JavaScript?
Use JSON.stringify(data, null, 2) — the third argument sets the indentation. Pass a number (spaces) or a string (e.g., ' ' for tabs). To log pretty JSON: console.log(JSON.stringify(data, null, 2)). In Node.js, write to a file with writeFileSync('out.json', JSON.stringify(data, null, 2)).
How do I pretty print JSON in Python?
Use json.dumps(data, indent=4) from the built-in json module. Add sort_keys=True to alphabetize keys. For non-ASCII characters, add ensure_ascii=False. To write to a file: json.dump(data, file, indent=4). From the command line: python -m json.tool input.json.
How do I pretty print JSON from the command line?
Two options: python -m json.tool input.json (built-in, no install) or jq '.' input.json (install via brew install jq). For curl output, pipe directly: curl -s https://api.example.com | jq '.'. jq adds color and is faster for large files.
How do I pretty print JSON in VS Code?
Open the JSON file and press Shift+Alt+F (Windows/Linux) or Shift+Option+F (Mac). Or right-click and choose "Format Document". For automatic formatting, add "editor.formatOnSave": true to your settings.
What is the difference between pretty print and minify?
Pretty printing adds whitespace for human readability. Minifying removes all whitespace for compact transmission. Both produce valid JSON — the data is identical. Use pretty-printed JSON for config files and debug output; use minified JSON for HTTP API responses and storage.
How do I pretty print JSON with tab indentation?
In JavaScript: JSON.stringify(data, null, '\t'). In Python: json.dumps(data, indent='\t'). With jq: jq --tab '.' input.json. Tabs are valid per the JSON specification, though spaces are more common in most style guides.
Can I pretty print JSON online?
Yes. Paste your JSON into the Jsonic JSON Formatter for instant pretty printing with syntax highlighting — all client-side, nothing sent to a server. Other options include jsonformatter.org and jsonlint.com.
Why does JSON.stringify produce null for certain values?
JSON.stringify drops object properties with undefined values, functions, and Symbol keys entirely (they are not valid JSON). Inside arrays, undefined and function values become null to preserve array length. Use a replacer function to handle these cases: JSON.stringify(data, (k, v) => v === undefined ? 'N/A' : v, 2).
Further reading and primary sources
- jq Manual — Complete jq command-line JSON processor manual
- Python json.tool — Python json.tool command-line JSON formatter