Skip to content

/commands/python/python-m-json-tool

python -m json.tool: pretty-print and validate JSON

verified onenvironmentlocal · windows 10.0.26200 arm64 · GNU bash 5.3.15 (Git Bash) · Python 3.13.15updated 2026-10-20
tool
Python
versions
Python 3.5+, python -m json: Python 3.14+
os
any

python -m json.tool file.json pretty-prints a JSON file, and exits with status 1 and an error message when the input is not valid JSON. It reads standard input when no file is given, so it also works in pipes. Since Python 3.14 the same CLI is available as python -m json; json.tool keeps working.

Pretty-print from a pipe

bash
echo '{"name": "errcodex", "tags": ["json", "cli"], "verified": true}' | python -m json.tool

Output

{
    "name": "errcodex",
    "tags": [
        "json",
        "cli"
    ],
    "verified": true
}

Validate a file

Invalid JSON prints the parser error with line and column, and the exit status is 1, which makes it usable in scripts and CI.

bash
printf '{"a": 1,}\n' > bad.json
python -m json.tool bad.json

Output · exit 1

Illegal trailing comma before end of object: line 1 column 8 (char 7)

Sort keys, change indentation, compact output

bash
echo '{"b": 2, "a": {"y": 1, "x": 2}}' > data.json
python -m json.tool --sort-keys --indent 2 data.json
python -m json.tool --compact data.json

Output

{
  "a": {
    "x": 2,
    "y": 1
  },
  "b": 2
}
{"b":2,"a":{"y":1,"x":2}}

Options

OptionEffectSince
infileFile to read (default: standard input)—
outfileFile to write (default: standard output)—
--sort-keysSort object keys alphabetically3.5
--indent NIndent with N spaces (default 4)3.9
--tabIndent with tabs3.9
--no-indentOne line, with spaces after separators3.9
--compactOne line, no extra whitespace3.9
--json-linesTreat every input line as a separate JSON document3.8
--no-ensure-asciiKeep non-ASCII characters instead of \uXXXX escapes3.9

Sources