This article will cover the process of pretty-printing JSON in Python. JSON (JavaScript Object Notation) is a popular data format with diverse uses in data manipulation and transmission. When dealing with large and complex JSON files in Python, it’s often useful to “pretty-print” them.
Python’s json Module
Python comes with a built-in module called json
for encoding and decoding JSON data. Among other functionalities, this module provides the necessary tools for pretty-printing JSON data.
Here’s how to pretty print JSON using the json
module:
import json
data = {
"name": "John",
"age": 30,
"city": "New York"
}
json_str = json.dumps(data, indent=4)
print(json_str)
In this script, json.dumps()
is a method that converts a Python object into a JSON string. The indent
the parameter specifies how many spaces to use as an indentation.
When we run this script, it outputs:
Pretty Printing JSON From a File
Often, you’ll need to Python pretty print JSON data stored in a file. Let’s take a look at how you can achieve this:
import json
with open('file.json', 'r') as f:
data = json.load(f)
pretty_json = json.dumps(data, indent=4)
print(pretty_json)
Here, json.load()
is used to load JSON data from a file. Then we pretty-print the data as before.
Output:
Pretty Printing JSON using pprint Module
Python also has a module named pprint
for pretty printing. This can be particularly useful for nested data structures. Let’s see how to use it for pretty printing JSON data:
import json
from pprint import pprint
data = {
"name": "John",
"age": 30,
"city": "New York"
}
pprint(data)
The pprint()
function prints the given data in a “pretty” format with both indentations and sorting.’
Output:
Conclusion
Python provides excellent support for pretty-printing JSON data, either from an object or from a file, using either the json
module or the pprint
module. This can be a great help when you’re working with complex JSON structures. Remember, pretty printing not only makes your JSON data more readable but also can help to detect errors or anomalies in your data.
You may like to read:
I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.