While converting a JSON object to string quite often it comes in a single line while you print the output. In this article we will see how to pretty print JSON string in Python. We will be using the function dumps() which is part of the default json module to pretty print JSON string.

json.dumps() function takes an argument indent which instructs the function add indentation after every block.  Take a look at the below example where it adds 4 indent after every section and there by format the JSON string.

Example Python Pretty Print JSON String

import json
json_obj = { "employees": [{"name": "John Watson", "dateOfJoin": "01/01/2018", "active": "Yes", "awards": 1 } ]}
print("***************BEFORE ADDING INDENT************")
print(json.dumps(json_obj))
print("\n***************AFTER ADDING INDENT************")
print(json.dumps(json_obj,indent=4))

Output:

***************BEFORE ADDING INDENT************
{"employees": [{"name": "John Watson", "dateOfJoin": "01/01/2018", "active": "Yes", "awards": 1}]}

***************AFTER ADDING INDENT************
{
    "employees": [
        {
            "name": "John Watson",
            "dateOfJoin": "01/01/2018",
            "active": "Yes",
            "awards": 1
        }
    ]
}
Python Pretty Print JSON String
Tagged on: