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.
A JSON response is on one line and jq is not installed, but Python is.
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: $?"{
"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: 1json.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.