TExcelTAD
Home › JSON › JSON Pretty Printing & Minifying

JSON Pretty Printing & Minifying

The same JSON data can be written in many ways. Whitespace between tokens has no meaning, so you can choose a layout for humans (pretty printed) or for machines (minified). Converting between the two never changes the data.

Pretty printed vs minified

Pretty printed JSON puts each value on its own line and indents nested levels:

json
{
  "name": "Sensor 4",
  "readings": [
    21.5,
    21.7
  ],
  "online": true
}

Minified JSON removes every unnecessary character:

json
{"name":"Sensor 4","readings":[21.5,21.7],"online":true}
Pretty printed Minified
Best for Reading, code review, config files, diffs Network transfer, storage
Size Larger Smallest possible
Typical indent 2 spaces (sometimes 4 or a tab) none

Pretty printing in the playground

The json playground on this site always pretty prints with 2 spaces. Paste any minified JSON and press ▶ Run:

json · try it yourself
{"id":17,"user":{"name":"Vy","roles":["editor","viewer"]},"settings":{"theme":"dark","fontSize":15},"lastLogin":null}
Valid JSON: object with 4 keys
{
  "id": 17,
  "user": {
    "name": "Vy",
    "roles": [
      "editor",
      "viewer"
    ]
  },
  "settings": {
    "theme": "dark",
    "fontSize": 15
  },
  "lastLogin": null
}

Pretty printing in JavaScript

JSON.stringify(value, null, space) controls the indentation. To re-format existing JSON text, parse it and stringify it again:

js · try it yourself
const minified = '{"id":17,"tags":["a","b"],"meta":{"ok":true}}';
const data = JSON.parse(minified);

console.log(JSON.stringify(data, null, 4));   // 4 spaces
console.log(JSON.stringify(data, null, "\t").replaceAll("\t", "→ "));  // tabs, made visible
{
    "id": 17,
    "tags": [
        "a",
        "b"
    ],
    "meta": {
        "ok": true
    }
}
{
→ "id": 17,
→ "tags": [
→ → "a",
→ → "b"
→ ],
→ "meta": {
→ → "ok": true
→ }
}

Minifying in JavaScript

JSON.stringify without a space argument produces minified output. Parsing first guarantees that only insignificant whitespace is removed — spaces inside strings stay untouched:

js · try it yourself
const pretty = `{
  "title": "Hello   World",
  "items": [
    1,
    2
  ]
}`;

const mini = JSON.stringify(JSON.parse(pretty));
console.log(mini);
console.log(`Size: ${pretty.length} -> ${mini.length} characters`);
{"title":"Hello   World","items":[1,2]}
Size: 61 -> 39 characters

Note: Never minify JSON with a regex like text.replace(/\s+/g, "") — it would also delete the spaces inside "Hello World".

Sorting keys for stable output

When JSON files are stored in Git, sorted keys make diffs smaller and comparisons easier. JavaScript has no built-in option for that, but a replacer function can do it:

js · try it yourself
function sortKeys(key, value) {
  if (value && typeof value === "object" && !Array.isArray(value)) {
    return Object.fromEntries(Object.entries(value).sort(([a], [b]) => a.localeCompare(b)));
  }
  return value;
}

const data = { zeta: 1, alpha: { gamma: 3, beta: 2 }, list: [{ y: 1, x: 2 }] };
console.log(JSON.stringify(data, sortKeys, 2));
{
  "alpha": {
    "beta": 2,
    "gamma": 3
  },
  "list": [
    {
      "x": 2,
      "y": 1
    }
  ],
  "zeta": 1
}

Compact but readable: one record per line

For lists of records, a middle ground is handy: each item minified on its own line. It's easy to scan and keeps diffs line-based:

js · try it yourself
const rows = [
  { id: 1, name: "Pen", price: 1.2 },
  { id: 2, name: "Notebook", price: 3.5 },
  { id: 3, name: "Bag", price: 25 },
];

const text = "[\n" + rows.map((r) => "  " + JSON.stringify(r)).join(",\n") + "\n]";
console.log(text);
console.log(JSON.parse(text).length, "rows - still valid JSON");
[
  {"id":1,"name":"Pen","price":1.2},
  {"id":2,"name":"Notebook","price":3.5},
  {"id":3,"name":"Bag","price":25}
]
3 rows - still valid JSON

Pretty printing on the command line

You don't need to write code to format a file:

bash
python3 -m json.tool data.json          # pretty print (4 spaces)
python3 -m json.tool --compact data.json  # minify
jq . data.json                           # pretty print with colours
jq -c . data.json                        # minify

Size matters less than you think

Minifying saves bytes, but HTTP compression (gzip, Brotli) shrinks repeated whitespace extremely well. For APIs, compression usually matters more than minification. Still, there's no reason to send indentation over the network — servers typically send minified JSON and developers pretty print it in their tools.

Test yourself

How do you pretty print an object with 2-space indentation in JavaScript?

  1. JSON.stringify(obj, 2)
  2. JSON.stringify(obj, null, 2)
  3. JSON.pretty(obj)
  4. JSON.format(obj, 2)

Why is text.replace(/\s+/g, "") a bad way to minify JSON?

  1. It is too slow
  2. It also removes spaces inside string values
  3. It removes commas
  4. Regexes cannot read JSON

Does pretty printing change the data?

  1. Yes, numbers are rounded
  2. Yes, keys are sorted
  3. No, only insignificant whitespace changes
  4. Only for arrays