Working with JSON data in Python is common, and the built-in json
module provides powerful tools for handling it. When dealing with complex JSON structures, the default output can be difficult to read. This tutorial will guide you through using Python to “pretty print” JSON, making it much more human-readable and easier to debug or analyze. We’ll explore how to format JSON strings and JSON files for clear and organized output.
1. Pretty Printing JSON Strings in Python
The json.dumps()
method in Python is essential for converting Python objects into JSON strings. To achieve pretty printing, you can utilize the indent
parameter within json.dumps()
. This parameter specifies the number of spaces to use for indentation, resulting in a nicely formatted JSON string.
Here’s how to pretty print a JSON string:
import json
json_data = '[{"ID":10,"Name":"Pankaj","Role":"CEO"},{"ID":20,"Name":"David Lee","Role":"Editor"}]'
json_object = json.loads(json_data)
json_formatted_str = json.dumps(json_object, indent=2)
print(json_formatted_str)
Output:
[
{
"ID": 10,
"Name": "Pankaj",
"Role": "CEO"
},
{
"ID": 20,
"Name": "David Lee",
"Role": "Editor"
}
]
Explanation:
- We begin by importing the
json
module, which is necessary for JSON operations in Python. json.loads(json_data)
parses the input JSON string (json_data
) and converts it into a Python object (in this case, a list of dictionaries).json.dumps(json_object, indent=2)
then takes this Python object and transforms it back into a JSON string. The crucial part isindent=2
, which instructsdumps()
to add indentation with 2 spaces at each level, making the JSON output visually structured and readable.- Finally,
print(json_formatted_str)
displays the pretty-printed JSON string to the console.
2. Pretty Printing JSON Files in Python
You might also need to pretty print JSON data directly from a JSON file. The json.load()
function is used to read JSON data from a file into a Python object. Then, similar to strings, json.dumps()
with the indent
parameter can be used to print it nicely.
Let’s consider a Cars.json
file with the following content (already in a pretty-printed format for demonstration):
Example of a pretty-printed JSON file structure, demonstrating readability with indentation.
[
{
"Car Name": "Honda City",
"Car Model": "City",
"Car Maker": "Honda",
"Car Price": "20,000 USD"
},
{
"Car Name": "Bugatti Chiron",
"Car Model": "Chiron",
"Car Maker": "Bugatti",
"Car Price": "3 Million USD"
}
]
Now, let’s see how Python handles printing this JSON file:
import json
with open('Cars.json', 'r') as json_file:
json_object = json.load(json_file)
print("Default Python Print:")
print(json_object)
print("nJSON Dumps without Indent:")
print(json.dumps(json_object))
print("nJSON Dumps with Indent=1:")
print(json.dumps(json_object, indent=1))
Output:
Default Python Print:
[{'Car Name': 'Honda City', 'Car Model': 'City', 'Car Maker': 'Honda', 'Car Price': '20,000 USD'}, {'Car Name': 'Bugatti Chiron', 'Car Model': 'Chiron', 'Car Maker': 'Bugatti', 'Car Price': '3 Million USD'}]
JSON Dumps without Indent:
[{"Car Name": "Honda City", "Car Model": "City", "Car Maker": "Honda", "Car Price": "20,000 USD"}, {"Car Name": "Bugatti Chiron", "Car Model": "Chiron", "Car Maker": "Bugatti", "Car Price": "3 Million USD"}]
JSON Dumps with Indent=1:
[
{
"Car Name": "Honda City",
"Car Model": "City",
"Car Maker": "Honda",
"Car Price": "20,000 USD"
},
{
"Car Name": "Bugatti Chiron",
"Car Model": "Chiron",
"Car Maker": "Bugatti",
"Car Price": "3 Million USD"
}
]
Explanation:
- We open
Cars.json
in read mode ('r'
) and usejson.load(json_file)
to parse the JSON data from the file intojson_object
. - The first
print(json_object)
shows Python’s default representation, which is a Python list of dictionaries, not JSON formatted. print(json.dumps(json_object))
demonstratesjson.dumps()
without theindent
parameter. It produces a compact, single-line JSON string, less readable for complex data.print(json.dumps(json_object, indent=1))
showcases the effect of theindent
parameter. Even withindent=1
, the output is significantly more readable, with each level of the JSON structure indented, enhancing clarity. You can adjust the indent value (e.g.,indent=4
for even more indentation) to suit your readability preferences.
References
Thanks for exploring pretty printing JSON in Python with the DigitalOcean Community. To further enhance your development environment, consider our offerings for compute, storage, networking, and managed databases.