How to pretty print JSON file
Pretty printing a JSON file in python is easy. Python provides a module called JSON to deal with JSON files. This module provides a lot of useful method including a method called dumps to pretty print JSON content.
In this post, I will show you how to pretty print JSON data in python with examples.
Example to pretty print :
Let’s consider the below example :
import json
data = '[{"name" : "Alex", "age" : 19},{"name" : "Bob", "age" : 18},{"name" : "Charlie", "age" : 21}]'
json_obj = json.loads(data)
pretty_obj = json.dumps(json_obj)
print(pretty_obj)
Here, data is the given JSON. json.loads converts the JSON data to a JSON object. We are using json.dumps to convert that JSON object. If you execute this program, it will give one output as like below :
Not a pretty print ! Because we need to specify the indent level in the dumps method :
pretty_obj = json.dumps(json_obj, indent=4)
Not it will give the required result :
Read JSON file and pretty print data :
Create one new file example.json and put the below JSON data :
[{"name" : "Alex", "age" : 19},{"name" : "Bob", "age" : 18},{"name" : "Charlie", "age" : 21}]'
In the same folder, create one python file to read the contents from this file :
import json
with open('example.json', 'r') as example_file:
json_obj = json.load(example_file)
pretty_obj = json.dumps(json_obj, indent=4)
print(pretty_obj)
Note that we are using load(), not loads() to read the content from a file. It will pretty print the file data.
Write pretty print JSON data to a file :
We can also use the above method to pretty print data to a separate file.
import json
data = '[{"name" : "Alex", "age" : 19},{"name" : "Bob", "age" : 18},{"name" : "Charlie", "age" : 21}]'
example_file = open('example.json', 'w');
json_obj = json.loads(data)
pretty_obj = json.dumps(json_obj, indent=4)
example_file.write(pretty_obj)
example_file.close()
If you open the example.json file, it will looks as like below :