python_json_beautifier
A small Python tool that pretty-prints JSON data.
python_json_beautifier is a two-line example I put together in 2016 for printing a Python dictionary or JSON data with readable indentation. It uses no external library; Python's own json module does the work.
Purpose
API responses and configuration data are usually carried as JSON, a text format made of key and value pairs. This data often arrives as a single line with no spaces, and nested fields are hard to read that way. I wrote this example to note down the shortest way to show JSON data neatly indented and with sorted keys, without installing any extra package. It is part of a small series, together with the HTML, CSS, JavaScript, SQL and XML indenting examples I made on the same day.
How it works
The script imports the json module and passes a sample dictionary to json.dumps with two settings. indent=4 indents each level by four spaces and puts every key on its own line. sort_keys=True sorts the keys alphabetically. This way, when I print the same data at different times, the keys always come out in the same order, which makes comparing two outputs easier. The result is printed to the screen.
Key features
- It uses only the Python standard library, so nothing needs to be installed.
- Because it sorts the keys, it makes comparing different outputs easier.
Technical stack
The code is written in Python and uses only the json module from the standard library. The example uses Python 2 syntax, where print is written without parentheses.
Status
This is a note-style example and has not been updated since 2016. Turning the print line into a function call is enough to run it on Python 3.
Use cases
- It can be used to make a JSON response from an API readable before looking into it.
- It helps write the contents of a dictionary to a log in a tidy form while debugging.
- It can be used to put the keys of two JSON outputs in the same order before comparing them.
- Category
- Developer tools
- Year
- 2016
Technologies
- Python
- JSON
Links
- GitHub https://github.com/muslu/python_json_beautifier