Python pretty print json

In this post, we will see how to pretty print JSON in Python.

We can use the Python JSON module to pretty-print JSON data. We can use json’s dumps() method with indent parameter to pretty print json data.

Python pretty print json string

Let’s understand this with the help of example.

Output:

[
{
“ID”: 101,
“Name”: “India”,
“Population”: “20000”
},
{
“ID”: 201,
“Name”: “Bhutan”,
“Population”: “3000”
}
]

Explanation

  1. Import json module
  2. Use json’s loads() method to convert json string json_countries to json object json_obj_countries
  3. Use json’s dumps() method to convert json object json_obj_countries to pretty print json data string json_pretty_str
  4. Print the string json_pretty_str

Python pretty print json File

We can first read json file into string with open() function
Let’s understand this with the help of example.
Here is json file which we are going to read.

EmployeesJsonFile

Output:

[{‘Employee ID’: 101, ‘Employee Name’: ‘Arpit’, ‘Age’: ’24’}, {‘Employee ID’: 202, ‘Employee Name’: ‘John’, ‘Age’: ’30’}] ========================================
[
{
“Employee ID”: 101,
“Employee Name”: “Arpit”,
“Age”: “24”
},
{
“Employee ID”: 202,
“Employee Name”: “John”,
“Age”: “30”
}
]

Explanation

  1. Import json module
  2. Use open(‘Employees.json’, ‘r’) function to read file into json_file
  3. Use json’s load() method to convert file object json_file to json object json_obj_countries
  4. Use json’s dumps() method to convert json object json_obj_countries to pretty print json data string json_pretty_str
  5. Print the string json_pretty_str

You can use indent=$space with dumps to pretty print json string.

For example:
json_pretty_str = json.dumps(json_obj_countries, indent=2) will output as:

whereas, json_pretty_str = json.dumps(json_obj_countries, indent=4) will output as:

That’s all about python pretty print json.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *