The mechanism: JSON.stringify's third argument
In JavaScript, pretty-printing is built directly into the serializer — JSON.stringify(value, null, 2) — where the third argument controls indentation: a number sets that many spaces per level, and a string (like "\t") uses that exact string as the indent unit instead.
JSON.stringify({a: 1, b: [1, 2]}, null, 2)
// {
// "a": 1,
// "b": [
// 1,
// 2
// ]
// }
Omitting the third argument (or passing nothing) produces minified, single-line output — the same data, just without the whitespace that makes nested structure visually obvious.
2 spaces, 4 spaces, or tabs — mostly a style choice
There's no functional difference between indent widths; all are equally valid JSON once parsed, since whitespace between tokens carries no meaning to a JSON parser. The common convention is 2 spaces (compact, widely used in JavaScript/web tooling) or 4 spaces (more common in some other language ecosystems) — pick one and stay consistent within a project, since mixed indentation in checked-in files creates noisy diffs for no functional benefit.
When pretty-printing actively hurts
- Large payloads over the network. Whitespace adds real bytes with zero semantic value — production API responses should be minified (no pretty-printing) to save bandwidth; pretty-print only for human inspection, in development tools or debug logs.
- Deeply nested, very large documents. Pretty-printing a multi-megabyte deeply nested JSON file can produce an enormous, barely-more-readable text file — for genuinely large data, a JSON tree viewer (collapsible nested nodes) is far more useful than flat indentation.
Common mistakes
- Shipping pretty-printed JSON in production API responses. The added whitespace is pure overhead once a human isn't the consumer — minify for anything machine-to-machine.
- Assuming indentation affects the parsed value. It doesn't —
{"a":1}and a multi-line indented version of the same object parse to an identical structure. - Mixing indent styles across a codebase. Pick 2 or 4 spaces (or tabs) and enforce it consistently, ideally via a formatter/linter rather than manual discipline.
FAQ
Does pretty-printing change the meaning of JSON data?
No — whitespace between JSON tokens is purely cosmetic; a minified and a pretty-printed version of the same document parse to identical values.
Should API responses be pretty-printed by default?
No — minified JSON saves real bandwidth for machine-to-machine communication; reserve pretty-printing for human-facing debugging and development tools.
Is 2-space or 4-space indentation "more correct"?
Neither — it's a style convention with no functional impact; consistency within a project matters more than which width you pick.
Pretty-print (or minify) JSON instantly with the JSON Toolkit — processed entirely in your browser.