All articles

How to pretty print JSON in JavaScript, Python and the terminal

· 4 min read

JSON arrives compact: an API response on one line, a log entry, a config value from an environment variable. Reading it means adding line breaks and indentation, which every language can do with its own JSON library. This guide shows the standard way in JavaScript, Python and the shell, plus the options and errors you will meet along the way.

Pretty print JSON in JavaScript

JSON.stringify takes three arguments: the value, an optional replacer, and the indentation. Pass null as the replacer and a number of spaces as the third argument:

const user = { id: 7, name: "Ada", roles: ["admin", "dev"], active: true };

console.log(JSON.stringify(user, null, 2));
// {
//   "id": 7,
//   "name": "Ada",
//   "roles": [
//     "admin",
//     "dev"
//   ],
//   "active": true
// }

The third argument can also be a string, used as the indent for each level. "\t" gives tab indentation:

JSON.stringify(user, null, "\t");

If you start from a JSON string rather than an object, parse it first. JSON.stringify on a string only adds quotes and escapes:

const text = '{"id":7,"name":"Ada"}';
const pretty = JSON.stringify(JSON.parse(text), null, 2);

Sort keys for stable output

JSON.stringify keeps the insertion order of keys. When you want output that diffs cleanly, for example in snapshots or committed fixtures, sort the keys recursively first:

function sortKeys(value) {
  if (Array.isArray(value)) return value.map(sortKeys);
  if (value && typeof value === "object") {
    return Object.fromEntries(
      Object.keys(value).sort().map((key) => [key, sortKeys(value[key])]),
    );
  }
  return value;
}

JSON.stringify(sortKeys(user), null, 2);

Arrays keep their order: in JSON, the position of an array item is part of the data.

Pick or transform fields with the replacer

The second argument controls what gets written. An array of key names keeps only those keys, at every level:

JSON.stringify(user, ["id", "name"], 2);
// { "id": 7, "name": "Ada" } (indented)

A function receives each key and value and returns what to write. Returning undefined drops the key, which is handy for hiding secrets in logs:

JSON.stringify(config, (key, value) => (key === "password" ? undefined : value), 2);

In the browser console and Node.js

The browser console already renders objects as an expandable tree, so console.log(obj) is often enough. For copy-pasteable output, Chrome and Firefox DevTools provide copy(JSON.stringify(obj, null, 2)), which puts the formatted text on the clipboard.

In Node.js, console.dir(obj, { depth: null }) prints nested objects without collapsing them to [Object], but its output is JavaScript syntax, not JSON. Use JSON.stringify when the result must be valid JSON.

Pretty print JSON in Python

The json module's dumps function has the same idea: an indent argument.

import json

user = {"id": 7, "name": "Zoë", "roles": ["admin", "dev"]}

print(json.dumps(user, indent=2, ensure_ascii=False, sort_keys=True))

Three arguments matter in practice:

  • indent=2 adds line breaks and two spaces per level. indent="\t" uses tabs.
  • ensure_ascii=False writes characters like ë as they are. The default, True, escapes them as \u00eb, which is valid but hard to read.
  • sort_keys=True sorts object keys, for the same reason as in JavaScript.

To format a file in place, read it, parse it and write it back:

import json
from pathlib import Path

path = Path("data.json")
data = json.loads(path.read_text(encoding="utf-8"))
path.write_text(json.dumps(data, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")

For quick inspection of nested Python objects that aren't JSON, pprint.pprint exists too, but like Node's console.dir it prints Python syntax (single quotes, True, None), not JSON.

Pretty print JSON in the terminal

jq

jq is the standard command-line JSON processor, available in most package managers. The filter . means "the whole input", so this prints it formatted and colored:

jq . data.json
curl -s https://api.github.com/repos/jqlang/jq | jq .

Useful flags:

  • --indent 4 changes the indentation (2 is the default), and --tab uses tabs.
  • -S sorts keys.
  • -c does the opposite and prints compact output, one value per line.

Because jq is a full query language, the same command can also pick out fields, for example jq '.items[].name'.

python -m json.tool

If Python is installed, you already have a formatter:

python3 -m json.tool data.json
cat data.json | python3 -m json.tool --sort-keys --no-ensure-ascii

Since Python 3.9 it also accepts --indent 4, --tab and --compact. It doesn't color the output, but it's always there on machines where installing jq isn't an option.

Node.js one-liner

With only Node.js available:

node -e 'let s="";process.stdin.on("data",d=>s+=d).on("end",()=>console.log(JSON.stringify(JSON.parse(s),null,2)))' < data.json

Errors that stop formatting

Formatting starts with parsing, so invalid JSON fails before any indentation happens. The common causes are trailing commas, single quotes and unquoted keys; the guide to checking whether a string is valid JSON covers them in detail. A few errors come from JSON.stringify itself:

Error Cause Fix
TypeError: Converting circular structure to JSON An object refers to itself, directly or through children. Remove the cycle, or use a replacer that skips already seen objects.
TypeError: Do not know how to serialize a BigInt The value contains a BigInt. Convert it in a replacer: (k, v) => typeof v === "bigint" ? v.toString() : v.
A Map or Set prints as {} They have no own enumerable properties. Convert first: Object.fromEntries(map) or [...set].

Some values are silently dropped rather than reported: undefined, functions and symbols disappear from objects and become null inside arrays, and NaN and Infinity become null. Dates become ISO strings through their toJSON method.

Large files and number precision

Two limits are worth knowing before you format big or numeric-heavy data:

  • Memory. JSON.parse and json.loads load the whole document. For multi-gigabyte files, use a streaming tool such as jq --stream, or process JSON Lines one line at a time.
  • Large integers. JavaScript numbers are 64-bit floats, so integers above Number.MAX_SAFE_INTEGER (9,007,199,254,740,991) lose precision when parsed. A pretty printer built on JSON.parse will rewrite 12345678901234567890 as 12345678901234567000. Python's json module keeps integers exact, and jq 1.7 and later preserve the original literal of large numbers it doesn't modify. If IDs are that large, send them as strings.

Choosing an indentation

Two spaces is the most common choice for JSON and keeps deeply nested data narrow. Four spaces reads better for some people; tabs let each editor pick the width. What matters more is consistency: pick one, set it in your formatter or editor config, and sort keys where you compare files.

Frequently asked questions

What is the maximum indentation JSON.stringify accepts?

A number above 10 is treated as 10, and a string longer than 10 characters is cut to its first 10. Use 2 or 4 in practice.

Does pretty printing change the data?

No. It only adds whitespace between tokens. Whitespace inside strings is part of the data and is never touched, so parsing the pretty and the compact version gives the same value.

Why does python -m json.tool show \u00e9 instead of é?

It escapes non-ASCII characters by default. Add --no-ensure-ascii on the command line, or pass ensure_ascii=False to json.dumps in code.

How do I pretty print JSON that is already a string?

Parse it first, then stringify it: JSON.stringify(JSON.parse(text), null, 2). Calling JSON.stringify on the string directly only wraps it in quotes.

Further reading