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.
Table of Contents
Python pretty print json string
Let’s understand this with the help of example.
1 2 3 4 5 6 7 8 9 10 11 12 |
import json json_countries = '[{"ID":101,"Name":"India","Population":"20000"},' \ '{"ID":201,"Name":"Bhutan","Population":"3000"}]' json_obj_countries = json.loads(json_countries) json_pretty_str = json.dumps(json_obj_countries, indent=2) print(json_pretty_str) |
Output:
{
“ID”: 101,
“Name”: “India”,
“Population”: “20000”
},
{
“ID”: 201,
“Name”: “Bhutan”,
“Population”: “3000”
}
]
Explanation
- Import json module
- Use json’s
loads()
method to convert json stringjson_countries
to json objectjson_obj_countries
- Use json’s
dumps()
method to convert json objectjson_obj_countries
to pretty print json data stringjson_pretty_str
- 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.
1 2 3 4 5 6 7 8 9 10 11 |
import json with open('Employees.json', 'r') as json_file: json_obj_countries = json.load(json_file) print(json_obj_countries) print("========================================") json_pretty_str = json.dumps(json_obj_countries, indent=2) print(json_pretty_str) |
Output:
[
{
“Employee ID”: 101,
“Employee Name”: “Arpit”,
“Age”: “24”
},
{
“Employee ID”: 202,
“Employee Name”: “John”,
“Age”: “30”
}
]
Explanation
- Import json module
- Use open(‘Employees.json’, ‘r’) function to read file into
json_file
- Use json’s
load()
method to convert file objectjson_file
to json objectjson_obj_countries
- Use json’s
dumps()
method to convert json objectjson_obj_countries
to pretty print json data stringjson_pretty_str
- 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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
[ { "Employee ID": 101, "Employee Name": "Arpit", "Age": "24" }, { "Employee ID": 202, "Employee Name": "John", "Age": "30" } ] |
whereas, json_pretty_str = json.dumps(json_obj_countries, indent=4)
will output as:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
[ { "Employee ID": 101, "Employee Name": "Arpit", "Age": "24" }, { "Employee ID": 202, "Employee Name": "John", "Age": "30" } ] |
That’s all about python pretty print json.