What "formatting" actually means
A JSON document is a string. Two strings can encode the exact same data: {"a":1,"b":2} and a sprawled, indented version with sorted keys both decode to the same JavaScript object. Formatting is just choosing how to render the bytes — it never changes meaning.
That matters because three operations get lumped together in conversation: pretty-printing (adding whitespace for humans), minifying (stripping every optional byte), and sorting keys (alphabetizing object properties for stable diffs). They are independent choices. You can minify a sorted document, pretty-print an unsorted one, or any combination.
The browser's JSON.stringify handles all three with two arguments — a replacer (rarely useful) and a space parameter that controls indentation. Everything in this post is a wrapper around those primitives.
Pick an indent and stick with it
The indent debate is a proxy war. The real question is: does your repo enforce a convention? If yes, match it. If no, use 2 spaces — npm, the TypeScript compiler, and Prettier all default to 2 spaces, so most tooling around you already speaks it.
Tabs are technically valid (the JSON spec allows any combination of spaces, tabs, and newlines as separators) but most JSON consumers either re-render to spaces or display tabs at whatever width the viewer prefers. Indent-sensitive workflows like YAML do not exist here. The choice is purely cosmetic.
// 2-space — the default everywhere
{
"name": "ada",
"skills": ["math", "engineering"]
}
// 4-space — easier to scan at the cost of horizontal real estate
{
"name": "ada",
"skills": ["math", "engineering"]
}One thing that does matter: be consistent inside a single file. Mixed indentation is what makes some pretty-printers misbehave — a leading tab on one line and spaces on the next can desync line-number reporting in error messages. Run the file through a formatter once and commit the result.
Sort keys for deterministic diffs
By default JSON.stringify preserves the insertion order of object keys. That is fine for ephemeral payloads but disastrous for two things: file hashing and version control diffs. If your build process generates a JSON file from a hash map whose iteration order is undefined, every build produces a different string with the same data.
The fix is to sort keys alphabetically before stringifying. The recursive version is short:
const sortKeys = (v) => {
if (Array.isArray(v)) return v.map(sortKeys);
if (v && typeof v === 'object') {
return Object.keys(v).sort().reduce((acc, k) => {
acc[k] = sortKeys(v[k]);
return acc;
}, {});
}
return v;
};
const stable = JSON.stringify(sortKeys(data), null, 2);Note that arrays keep their order — arrays in JSON are ordered by definition, so sorting them would change meaning. Only object keys get reordered.
This matters most for lockfiles, generated schemas, and any JSON you fingerprint with a hash for cache invalidation. If you ever see a "no changes" PR that only shuffles keys, the file is being regenerated without sorting.
When to minify instead
Gzip catches most of the win from whitespace, which is why minifying API responses on top of gzip gives diminishing returns. But there are contexts where gzip is unavailable, and that is where minification still matters:
- JWT payloads — base64-encoded, no compression layer underneath.
localStorageandsessionStorage— text-only, no compression, 5–10 MB quota.- URL-encoded state — every byte costs you against the URL length limit.
- JSON embedded in HTML
data-attributes — uncompressed by default. - IndexedDB blobs when you read the same record thousands of times.
Minifying is the cheapest JSON.stringify call there is — just omit the space argument:
const minified = JSON.stringify(data); // no space → no whitespaceTypical reduction from pretty-printed JSON is 20% to 45%, depending on how nested the structure is. Combined with gzip on the transport, total saving over un-minified, un-compressed JSON often lands in the 80–95% range.
Formatting in the browser
For one-off formatting, the fastest path is a browser tool that runs locally — no upload, no waiting. The JSON formatter on this site handles indent choice, key sorting, and minification in one panel. Paste, click, copy.
If you want to do it yourself in a snippet, the devtools console is enough:
// Format whatever is on the clipboard
const txt = await navigator.clipboard.readText();
console.log(JSON.stringify(JSON.parse(txt), null, 2));
// Or format the JSON response of the current page
fetch(location.href).then(r => r.json()).then(d =>
console.log(JSON.stringify(d, null, 2))
);Formatting in the terminal
When you are already in a shell, reach for jq. It is the de facto JSON Swiss army knife and a quarter-megabyte download:
# Pretty-print
cat data.json | jq
# Minify (one line, no whitespace)
cat data.json | jq -c
# Sort keys alphabetically
cat data.json | jq -S
# Format a piped API response
curl -s https://api.github.com/users/torvalds | jqIf jq is not installed, Python and Node both ship pretty-printers:
python3 -m json.tool < data.json
node -e "console.log(JSON.stringify(JSON.parse(require('fs').readFileSync(0,'utf8')),null,2))" < data.jsonFor large files (over a few hundred MB), jq and the language-native parsers all load the document into memory. At that scale switch to streaming — jq has a --stream mode that emits per-token events without building the full tree.
Formatting from your code
Most languages have one obvious way. Memorise the signatures.
// JavaScript / TypeScript
JSON.stringify(data, null, 2);
// Python
import json
json.dumps(data, indent=2, sort_keys=True)
// Go
import "encoding/json"
b, _ := json.MarshalIndent(data, "", " ")
// Rust (serde_json)
serde_json::to_string_pretty(&data)?
// Java (Jackson)
objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(data);One thing to watch in JavaScript: JSON.stringify swallows undefined values, function references, and symbols silently. If you serialize {a: 1, b: undefined} you get {"a":1} back, not an error. That matters when your data shape is supposed to round-trip through JSON — log a warning at the boundary if you cannot guarantee inputs are JSON-safe.
Edge cases that bite
NaN and Infinity
None of these are valid JSON. JSON.stringify(NaN) returns the string "null" — it does not throw. If your data might contain non-finite numbers, decide upfront whether to convert them to null, drop the key, or refuse the data.
Big integers
JavaScript numbers lose precision above 253. Serializing a Twitter snowflake ID like 1234567890123456789 through JSON.parse mutates the value. Either keep the IDs as strings in the JSON or use a parser that preserves precision (JSON.parse with a reviver, or a library like lossless-json).
Circular references
JSON.stringify throws on cycles. If you are formatting a graph (DOM nodes, ORM models with back-references), pass a replacer that tracks seen objects or pre-process the structure into a tree.
Trailing newline
Most pretty-printers do not add a trailing newline. POSIX text files should end with one, and some tools (older versions of jq, GitHub's web diff) display the missing newline noisily. Add it explicitly if your build pipeline cares.
Pre-validate before you format
A formatter is downstream of a parser. If JSON.parse throws, no amount of indentation will help. When the input is hand-written or copy-pasted from a non-JSON source (config with comments, JavaScript object literal), run it through the validator first to get a line and column, or the repair tool if you want the common cases (trailing commas, single quotes, JS comments) auto-fixed.