Tuesday, August 31, 2021

Will McGugan: 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:

© 2021 Will McGugan

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": [
        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:

© 2021 Will McGugan

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:

© 2021 Will McGugan

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.



from Planet Python
via read more

No comments:

Post a Comment

TestDriven.io: Working with Static and Media Files in Django

This article looks at how to work with static and media files in a Django project, locally and in production. from Planet Python via read...