Pretty printing makes a json file visually appealing and easy to edit. If you have a JSON file that is compact or not visually appealing, you can easily convert it in Python to a pretty print form.

Pretty Print function in Python

Below is a function that converts any json information into its pretty print version. You can also optionally sort the output by keys or change the pretty print indent size. The function automatically identifies the type of the json data which means you can either pass a json file path, raw json string or a python dictionary, and the function will process it accordingly.

import json
def make_json_pretty(json_info,indent=4,sort=True):
    if type(json_info) is str:         #if json_info is a string
        if json_info.strip()[0]=="{":  #if json_info is raw json data
            json_data=json.loads(json_info)
        else:                          #if json_info is file path
            with open(json_info) as json_file:
                json_data = json.load(json_file)
    elif type(json_info) is dict:      #if json_info is a python dictionary
        json_data = json_info
    else:                              #if json_info is not json data or file path
        raise Exception("first parameter should be JSON file path or JSON data")
    pretty_json = json.dumps(json_data, indent=4, sort_keys=sort)
    return pretty_json
Code language: Python (python)

Pretty Print via Command Line in Python 3

Starting from Python 3, you can pretty print a json file right from the command line! See example below.

python3 -m json.tool < path_to_my_json.jsonCode language: Bash (bash)

The above command will pretty print the JSON data in the console itself. Instead, if you want to save the pretty print version to another file redirect the output as follows.

python3 -m json.tool < path_to_my_json.json > path_to_pretty.jsonCode language: Bash (bash)

Download HitXP Mobile App

Get it on Google Play