Home »
Python »
Python Articles
Python Pretty Print JSON
By IncludeHelp Last updated : February 20, 2024
To make JSON string data more readable while printing or writing, you can use pretty printing by using the json.dumps() method along with two arguments indent and sort_keys.
The indent argument indents the JSON string and the sort_keys method sorts the JSON string in ascending order.
Example of Python Pretty Print JSON
This example demonstrates Python pretty print JSON.
# Importing json module
import json
# Creating a JSON string
student = '{"id":"09", "name": "Nitin", "department":"Finance"}'
# Converting JSON string to Python object
student_dict = json.loads(student)
# Pretty Printing JSON String
print(json.dumps(student_dict, indent=4, sort_keys=True))
Output
The output of the above program is:
{
"department": "Finance",
"id": "09",
"name": "Nitin"
}
To understand the above example, you should have the basic knowledge of the following Python topics: