Sub topic 7
Pretty-Printing JSON with the space Argument
This chapter assumes you know how JSON.stringify serializes objects and arrays, and that you have seen its second argument, the replacer. Here we focus on the third argument, space, which controls indentation.
By default, JSON.stringify produces compact output with no line breaks or extra spaces. That is ideal for sending data over a network. For config files, logs, and debugging, humans need something easier to read.
The Basic Pattern
Pass null as the replacer when you only want formatting, then pass the indentation as the third argument:
const config = {
name: "app",
port: 8080,
features: ["auth", "logs"],
db: {}
};
console.log(JSON.stringify(config));
// {"name":"app","port":8080,"features":["auth","logs"],"db":{}}
console.log(JSON.stringify(config, null, 2));
// {
// "name": "app",
// "port": 8080,
// "features": [
// "auth",
// "logs"
// ],
// "db": {}
// }Pretty-printing changes three things in the output:
- Each property and array element goes on its own line.
- Each nesting level is indented by the
spacevalue. - A single space follows every colon (
"name": "app").
Empty objects and arrays stay on one line as {} and [].
Numbers Versus Strings
The space argument accepts a number or a string, and the two behave differently.
| `space` value | Effect |
|---|---|
| Number 1–10 | Indent with that many spaces per level |
| Number above 10 | Treated as 10 |
| Number below 1 (0, negative) | No formatting, compact output |
| Fractional number (e.g. `2.7`) | Truncated to an integer (`2`) |
| String | That string is used as the indent, up to its first 10 characters |
| Empty string `""` | No formatting |
| Anything else (`true`, `{}`, `undefined`) | Ignored, compact output |
const data = { a: 1, b: [true] };
console.log(JSON.stringify(data, null, "\t"));
// {
// "a": 1,
// "b": [
// true
// ]
// }
console.log(JSON.stringify(data, null, "--"));
// {
// --"a": 1,
// --"b": [
// ----true
// --]
// }
console.log(JSON.stringify(data, null, 20) === JSON.stringify(data, null, 10)); // true
console.log(JSON.stringify(data, null, "abcdefghijklmnop").split("\n")[1]);
// abcdefghij"a": 1Tabs ("\t") and two or four spaces are the common choices. A non-whitespace string like "--" makes the nesting visible, but the result is no longer valid JSON. Use non-whitespace indents only for display.
Formatting Does Not Change the Data
JSON.parse ignores whitespace between tokens, so pretty and compact output parse to the same value:
const value = { id: 1, tags: ["x", "y"] };
const pretty = JSON.parse(JSON.stringify(value, null, 4));
const compact = JSON.parse(JSON.stringify(value));
console.log(JSON.stringify(pretty) === JSON.stringify(compact)); // trueWhitespace inside string values is never touched. Only the space between tokens changes.
Common Mistakes
- Forgetting the replacer slot.
JSON.stringify(obj, 2)passes2as the replacer. A number is not a function or an array, so it is ignored, and the output stays compact. WriteJSON.stringify(obj, null, 2). - Pretty-printing network payloads. Indentation can make output noticeably larger in bytes, especially for deeply nested data. Send compact JSON and format it only when people will read it.
- Missing trailing newline in files.
JSON.stringifynever adds a final newline. Many editors and linters expect one, so append"\n"when you write a file.
Exercise
What does JSON.stringify({ a: [1] }, 2) print, and how do you fix it to indent by two spaces?
Show answer
It prints {"a":[1]}. The 2 sits in the replacer position, where a number is ignored, so the output is compact. The fix is JSON.stringify({ a: [1] }, null, 2), which prints the object over several lines with "a" indented two spaces and 1 indented four spaces.
Exercise
Is the output of JSON.stringify({ a: 1 }, null, 15) different from JSON.stringify({ a: 1 }, null, 10)? Is JSON.stringify({ a: 1 }, null, "**") valid JSON?
Show answer
The two outputs are identical, because numeric space values are clamped to a maximum of 10. The "**" version is not valid JSON, because the asterisks appear outside any token, and JSON only allows whitespace there. JSON.parse would throw a SyntaxError on it.