A quick look at the json module in Python

If you ever need to work with JSON files in Python, you're going to encounter the module with the same name.

It help encode to and decode from JSON. Here are the basics:

➡ json.load imports contents from a JSON file to a Python object, based on conversion rules (object -> dict, array -> list/tuple, string-> str etc)

➡ json.dump performs the opposite operation - export to a file-like object

There are also the json.loads and json.dumps functions (notice the extra s) which apply to strings instead of files.

There's also the json.tool, which can validate and pretty-format a provided json file.

You can save that prettified json into another file, as follows:

python -m json.tool ugly_format.json pretty_format.json

No alt text provided for this image

Found it useful? Subscribe to my Analytics newsletter at notjustsql.com.