How to pretty print JSON in Python?


JSON (JavaScript Object Notation) is a lightweight data format used to interchange the data. It is human-readable and can be easily parsed and generated by machines. JSON is a text format that is independent of language.

This format of data is most commonly used to transmit and receive data between a web application and a server. The following examples show the JSON data format.

Example 1:

"{\"emp id\": \"54234\", \"name\": \"Adam\", “designation”: “sales manager” “salary”: 45000}"

Example 2:

Let’s say the file name is data.json. The given JSON data is in a prettier format.

{
   "students":[
      {
         "roll_no":"1",
         "name":"John",
         "total_marks":"67"
      },
      {
         "roll_no":"2",
         "name":"Ritesh",
         "total_marks":"83"
      },
      {
         "roll_no":"3",
         "name":"Vandna",
         "total_marks":"78"
      }
   ]
}

In this article, we will explain how to pretty print a JSON file in Python.

JSON pretty print

As I already discussed how to read, write or parse a JSON file in Python. Whenever we convert a python object into a JSON object the output of printing the JSON object is displayed the same as the Python dictionary format. The json.dumps()function of JSON module is used to convert a Python object to a JSON object.

To display this dictionary-like data of JSON file in a good and presentable format is called a pretty print of JSON data. This can be helpful in testing, analyzing, and debugging JSON data.

Example of JSON pretty print

The following example shows how to print JSON data with the proper indentation in a prettier format so that we can improve readability.

# Python program to demonstrate pretty-printing of JSON data
# Import JSON module
import json

# Initialize JSON data
json_data = '[ {"roll_no":1, "name":"John", "subjects": ["Java", "Data Structures"]}, \
	       {"roll_no":2, "name": "Ritesh", "subjects": ["Python", "AI"]} ]'

# Create Python object from JSON string data
obj = json.loads(json_data)

# Pretty Print JSON
json_formatted_data = json.dumps(obj, indent=3)
print(json_formatted_data)

When you execute this program it will print the data in a prettier format. You can see the output in the given image.

Pretty print JSON data in the terminal

You can also pretty-print the JSON data in Python from your command. Use the given command to pretty-print data of the file data.json.

cat data.json | python3 -m json.tool

When you execute this command it will pretty print the unformatted JSON data of the file data.json.

Conclusion

I hope now you understand how to pretty print JSON data in Python. Now if you have any query then write us in the comments below.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.