August 31, 2021 will

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:

Calling print_json with a string will decode the JSON and pretty print it.

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": [
            "Paul Atreides",
            "Vladimir Harkonnen",
            "Thufir Hawat",
    "atomic": (False, True, None),
from rich import print_json

Here's the output:

Calling the print_json function with a data keyword argument.

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:

Pretty printing a JSON file from the command line

This is admittedly a small addition to Rich but I'm already finding it helpful.

Follow @willmcgugan on Twitter for Rich and Textual updates.

Use Markdown for formatting
*Italic* **Bold** `inline code` Links to [Google]( > This is a quote > ```python import this ```
your comment will be previewed here
Łukasz Prokulski

Why not built-in pprint?

Will McGugan

No syntax highlighting, doesn't produce JSON, old-style formatting, etc.