Pretty printing JSON with Rich
If you work with JSON regularly (90% of Python developers I suspect) you might appreciate the print_json
function just landed in Rich v10.9.0
If you call this function with a string, Rich will decode the string, reformat it, and print it to the console with nice syntax highlighting. Here's an example:
from rich import print_json
print_json('{"foo": [false, true, null]}')
Here's the output:
Note that the atomic values false
, true
, and null
have their own color. I find this helpful when scanning a JSON blob.
If you call print_json
with a data
keyword argument it will encode that data and pretty print it in the same way.
data = {
"foo": [
3.1427,
(
"Paul Atreides",
"Vladimir Harkonnen",
"Thufir Hawat",
),
],
"atomic": (False, True, None),
}
from rich import print_json
print_json(data=data)
Here's the output:
Note that Rich will remove color if you pipe the output of your script to another program, so you can safely add syntax highlighting to your CLI tools.
You can also pretty print JSON files from the command line with the following:
python -m rich.json data.json
Here's an example of the output:
This is admittedly a small addition to Rich but I'm already finding it helpful.
Follow @willmcgugan on Twitter for Rich and Textual updates.
Why not built-in pprint? https://docs.python.org/3/library/pprint.html
No syntax highlighting, doesn't produce JSON, old-style formatting, etc.
Why doesn't this function show up in the official documentation?
Not sure when it was added, but it's in the docs now:
https://rich.readthedocs.io/en/stable/console.html?highlight=print_json#printing-json