Skip to content
shellhacks.dev
Python

Pretty-print JSON with the standard library

Pretty-print JSON with the standard library: python3 -m json.tool. It keeps key order by default, rejects invalid input with a position, and needs no jq.

1 min read
Summarize in AI

A JSON response is on one line and jq is not installed, but Python is.

Shell
echo '{"name":"demo","tags":["a","b"],"n":1}' | python3 -m json.tool
echo '{"b":1,"a":2}' | python3 -m json.tool --sort-keys --indent 2
echo '{"a": 1,}' | python3 -m json.tool; echo "exit: $?"
Text
{
    "name": "demo",
    "tags": [
        "a",
        "b"
    ],
    "n": 1
}
{
  "a": 2,
  "b": 1
}
Expecting property name enclosed in double quotes: line 1 column 9 (char 8)
exit: 1

json.tool reads standard input or a file, parses it with the json module and prints it with an indent, as described in the json.tool documentation. The key order of the input is kept unless you add --sort-keys. A trailing comma is not valid JSON, and the parser reports the line and column of the error and exits with status 1.

Non-ASCII characters are written as escape sequences by default, so add --no-ensure-ascii on Python 3.9 or later to keep them readable. The tool loads the whole document into memory, and the input must be a single JSON value, so a stream of JSON lines needs --json-lines from Python 3.8.

Share

More snippets

Python

Read a CSV file

Read a CSV file with csv.reader and open it with newline=''. Without that argument a line break inside a quoted field is changed before the parser sees it.

2 min read
Python

Generate a UUID

Generate a random UUID with uuid.uuid4() and a repeatable one with uuid.uuid5(namespace, name). The hex attribute gives the form without hyphens.

2 min read
Python

Base64 encode a string

Encode with base64.b64encode(), which takes and returns bytes, so encode the string first and decode the result. The URL-safe variant swaps two characters.

1 min read

Get new posts by email

One email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.