Sub topic 7
Pretty-Printing JSON with the space Argument
By default, JSON.stringify puts everything on one line. That works for machines but is hard for people to read. The third argument, space, adds line breaks and indentation. This chapter covers which values space accepts, how they are normalized internally, what the indented output looks like, and when compact output is the better choice.
This chapter assumes you already know the basic JSON.stringify(value) call, and that you know a replacer is the optional second argument. It also assumes you can run JavaScript in Node.js or a browser console.
The Shape of the Call
The full signature is:
JSON.stringify(value, replacer, space);You often want indentation without a replacer. In that case, pass null (or undefined) as the second argument so that space lands in the third position:
const config = { name: "api", port: 8080, features: ["auth", "cache"], limits: {} };
console.log(JSON.stringify(config));
// {"name":"api","port":8080,"features":["auth","cache"],"limits":{}}
console.log(JSON.stringify(config, null, 2));
// {
// "name": "api",
// "port": 8080,
// "features": [
// "auth",
// "cache"
// ],
// "limits": {}
// }Indented output differs from compact output in four ways:
- A newline follows every opening
{or[, and every member or element sits on its own line. - Each nesting level adds one more copy of the indent string.
- A colon is followed by a single space (
"port": 8080). Compact output has no space there. - Empty objects and arrays stay as
{}and[]. They are never expanded across lines.
Arrays are expanded as fully as objects, so a short list of numbers takes one line per element. Some formatting tools keep short arrays on a single line, but JSON.stringify has no option for that.
How space Is Normalized
space accepts either a number or a string. The engine turns it into an indent string, which the specification calls the gap, before it serializes anything. Most of the surprises with space come from these normalization rules.
Numbers
A number sets how many space characters each level adds:
const obj = { a: { b: 1 } };
console.log(JSON.stringify(obj, null, 4));
// {
// "a": {
// "b": 1
// }
// }
console.log(JSON.stringify(obj, null, 0)); // {"a":{"b":1}}
console.log(JSON.stringify(obj, null, -3)); // {"a":{"b":1}}
console.log(JSON.stringify(obj, null, 2.9)); // same as 2: fractions are truncated
const wide = JSON.stringify({ x: 1 }, null, 25);
console.log(wide.split("\n")[1].indexOf('"')); // 10: capped at 10 spacesAny value below 1 (zero, negative numbers, 0.5) gives compact output. Fractions are truncated toward zero, not rounded, so 2.9 behaves like 2. Anything above 10 is capped at 10. Infinity is also capped at 10. NaN becomes 0, so it gives compact output.
Strings
A string is used as the indent itself, cut to its first 10 characters:
const obj = { a: { b: 1 } };
console.log(JSON.stringify(obj, null, "\t"));
// {
// "a": {
// "b": 1
// }
// }
console.log(JSON.stringify(obj, null, "--"));
// {
// --"a": {
// ----"b": 1
// --}
// }
const long = JSON.stringify({ x: 1 }, null, "abcdefghijklmnop");
console.log(long.split("\n")[1]); // abcdefghij"x": 1
console.log(JSON.stringify(obj, null, "")); // {"a":{"b":1}}A tab ("\t") is the most common string choice. An empty string gives compact output.
Everything Else
Booleans, null, plain objects, and arrays are ignored, and the output is compact. Number and String wrapper objects are unwrapped first, so new Number(3) behaves like 3:
console.log(JSON.stringify({ a: 1 }, null, true)); // {"a":1}
console.log(JSON.stringify({ a: 1 }, null, [2])); // {"a":1}
console.log(JSON.stringify({ a: 1 }, null, new Number(3)));
// {
// "a": 1
// }You can check this directly:
const decorated = JSON.stringify({ a: 1 }, null, "--");
try {
JSON.parse(decorated);
} catch (err) {
console.log(err instanceof SyntaxError); // true
}Whitespace Does Not Change the Data
JSON ignores whitespace between tokens, so output indented with spaces or tabs parses back to exactly the same value as compact output:
const value = { id: 1, items: [{ sku: "A1", qty: 2 }], meta: {} };
const compact = JSON.stringify(value);
const pretty = JSON.stringify(value, null, 2);
console.log(compact === pretty); // false
console.log(JSON.stringify(JSON.parse(pretty)) === compact); // trueWhitespace inside string values is a different matter, because it belongs to the data. Indentation never touches it. A newline inside a string is always written as the escape \n, so a multi-line string value still takes one line in the output:
console.log(JSON.stringify({ note: "line one\nline two" }, null, 2));
// {
// "note": "line one\nline two"
// }The line breaks that JSON.stringify adds between members are always a single line feed (\n), on every platform. It never writes \r\n, even on Windows.
Combining space with a Replacer
space works with either kind of replacer. The replacer decides what goes into the output, and space decides how it is laid out:
const user = { id: 42, name: "Ada", email: "[email protected]", token: "xyz" };
console.log(JSON.stringify(user, ["id", "name"], 2));
// {
// "id": 42,
// "name": "Ada"
// }
console.log(
JSON.stringify(user, (key, value) => (key === "token" ? undefined : value), "\t")
);
// {
// "id": 42,
// "name": "Ada",
// "email": "[email protected]"
// }Properties that the replacer removes leave no blank lines or stray commas. The layout is built only from the members that remain.
The Cost of Readability
Indentation adds bytes. With small payloads the cost doesn't matter. With large or deeply nested data, it adds up quickly:
const data = {
users: [
{ id: 1, name: "Ada" },
{ id: 2, name: "Linus" }
]
};
const compact = JSON.stringify(data);
const pretty = JSON.stringify(data, null, 2);
console.log(compact.length); // 57
console.log(pretty.length); // 117Here the indented version is about twice the size. Indentation grows with depth, so deeply nested data inflates even more. Compression such as gzip removes much of this overhead on the wire, but the indented text still uses more memory and takes longer to build and parse.
| Use case | Recommended `space` | Reason |
|---|---|---|
| HTTP API responses | none | Smaller payloads; clients don't need formatting |
| Config files committed to git | `2` or `"\t"` | Readable, and diffs show one changed line per value |
| Debug output in a console | `2` | Easy to scan nested structure |
| Line-based logs (NDJSON) | none | Each record must fit on exactly one line |
| `localStorage` or cache entries | none | Storage quotas are small |
| Human-facing display only | any string | Decorative indents are acceptable if never re-parsed |
Writing Pretty JSON Files
Files such as package.json usually use 2-space indentation and end with a newline. JSON.stringify never adds a trailing newline, so you have to append it yourself. Without it, many editors and git diff report "No newline at end of file."
const fs = require("node:fs");
const settings = { theme: "dark", fontSize: 14, plugins: ["git", "lint"] };
fs.writeFileSync("settings.json", JSON.stringify(settings, null, 2) + "\n");
const loaded = JSON.parse(fs.readFileSync("settings.json", "utf8"));
console.log(loaded.plugins[1]); // "lint"Two things help keep diffs clean:
- Use the same
spacevalue every time you write the file. Switching between2and"\t"rewrites every line. - Keep property insertion order stable.
JSON.stringifywrites keys in the object's own key order: integer-like keys in ascending numeric order first, then string keys in insertion order. If you build the object in a different order, the file's key order changes too.
Reformatting Existing JSON Text
A common one-liner re-indents a compact JSON string:
const raw = '{"b":1,"a":[1,2,3]}';
console.log(JSON.stringify(JSON.parse(raw), null, 2));
// {
// "b": 1,
// "a": [
// 1,
// 2,
// 3
// ]
// }This round trip is not purely cosmetic. Parsing happens first, so anything that JSON.parse changes is lost before formatting:
- If a key appears twice, only the last value survives.
- Integers beyond
Number.MAX_SAFE_INTEGERlose precision (covered in the chapter on BigInt and numeric precision). - Number spellings are normalized:
1.0becomes1and1e3becomes1000.
For a file where every digit matters, use a formatter that works on tokens rather than parsed values.
Common Mistakes
| Mistake | Symptom | Fix |
|---|---|---|
| `JSON.stringify(obj, 2)` | Output stays compact; `2` is ignored as a replacer | Use `JSON.stringify(obj, null, 2)` |
| `space` of `"2"` (a string) | Indent is the literal character `2`, giving invalid JSON | Pass the number `2` |
| Expecting more than 10 spaces | Indent stops at 10 | Reconsider the design; 10 is a hard cap |
| Indented JSON in line-based logs | Records split across lines | Log compact output |
| Missing final newline in files | Noisy diffs and editor warnings | Append `"\n"` |
The "2" mistake happens when the value comes from a CLI flag or an environment variable. Convert it with Number(...) first.
Exercise
What does JSON.stringify({ a: [1] }, null, "12") print, and can JSON.parse read it back?
Show answer
It prints "{\n12\"a\": [\n1212 1\n12]\n}" in spirit; precisely, each level is indented with the string "12": line 1 is "{", line 2 is "12\"a\": [", line 3 is "12121", line 4 is "12]", line 5 is "}". The string "12" is used literally as the indent, not as a count. JSON.parse cannot read it back, because "12" before "a" is not whitespace, so it throws a SyntaxError.
Exercise
A script reads an INDENT environment variable and calls JSON.stringify(data, null, process.env.INDENT). With INDENT=4 the output looks wrong. Why, and how do you fix it?
Show answer
Environment variables are always strings, so space receives "4" and each level is indented with the character 4, which also makes the JSON invalid. Convert it first, for example JSON.stringify(data, null, Number(process.env.INDENT) || 0). A missing or non-numeric value then falls back to compact output.
Exercise
Predict the output of JSON.stringify({ list: [], obj: {}, n: 1 }, null, 3) and JSON.stringify({ n: 1 }, null, 0.99).
Show answer
The first gives "{", then three-space-indented lines "\"list\": [],", "\"obj\": {},", "\"n\": 1", then "}". Empty arrays and objects are never expanded. The second gives {"n":1}, because 0.99 truncates to 0, and any value below 1 means no indentation.
Exercise
Why might JSON.stringify(JSON.parse(text), null, 2) change more than whitespace in a JSON file?
Show answer
The text is parsed into JavaScript values before it is formatted. Duplicate keys collapse to the last value, integers beyond Number.MAXSAFEINTEGER lose precision, and number spellings like 1.0 or 1e3 are normalized to 1 and 1000. Formatting through parse is only safe when the data survives a round trip unchanged.