JSON (JavaScript Object Notation), has become the de facto standard for data exchange across the web. From configuring applications to transmitting data between APIs, its lightweight and human-readable format makes it incredibly versatile. However, while machines can easily process JSON in its most compact form – often minified into a single line – that efficiency can turn into a significant hurdle for human developers.
That’s where pretty-printing comes in. Pretty-printing JSON transforms these dense data strings into an organized, indented, and easily digestible structure. In Python, we can use the json module to pretty-print the JSON data. The json
module is recommended to work with JSON files. This article will guide you through the fundamental methods of pretty-printing JSON in Python, demonstrating how to convert raw JSON strings into beautifully formatted output.
We can use the dumps()
method to get the pretty formatted 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)
This outputs the formatted JSON:
[
{
"ID": 10,
"Name": "Pankaj",
"Role": "CEO"
},
{
"ID": 20,
"Name": "David Lee",
"Role": "Editor"
}
]
json.loads()
to create the JSON object from the JSON string.json.dumps()
method takes the JSON object and returns a JSON formatted string. The indent
parameter defines the indent level for the formatted string.Let’s see what happens when we try to print a JSON file data. The file data is saved in a pretty printed format.
import json
with open('Cars.json', 'r') as json_file:
json_object = json.load(json_file)
print(json_object)
print(json.dumps(json_object))
print(json.dumps(json_object, indent=1))
Output:
[{'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'}]
[{"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"}]
[
{
"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"
}
]
It’s clear from the output that we have to pass the indent value to get the JSON data into a pretty printed format.
When you make an API request, you often get a single, long line of JSON response to save bandwidth. This is incredibly difficult for humans to read and understand, especially for complex or deeply nested data. Pretty-printing transforms this unreadable string into a structured, indented, and human-readable format, making it far easier to identify correct data, missing fields, or unexpected errors.
Here’s an example of how to fetch an API response and pretty-print its content. We’re using the JSONPlaceholder API for testing.
import requests
import json
url = "https://jsonplaceholder.typicode.com/posts/1"
response = requests.get(url)
if response.status_code == 200:
data = response.json()
print(json.dumps(data))
print(json.dumps(data, indent=2))
else:
print(f"Error: {response.status_code}")
This will print the following output:
{"userId": 1, "id": 1, "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit", "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"}
{
"userId": 1,
"id": 1,
"title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
"body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
}
As you can see, the pretty printed JSON is easier to read and debug.
Traditional log messages are often plain text. When you need to log complex events, user actions, or system states that are best represented as JSON (e.g., a full request payload, an error context, or a processed data record), logging it as a single, unformatted string makes logs difficult to read, parse, and analyze. Pretty-printing JSON within your logs makes them immediately understandable, especially when manually sifting through log files or using log aggregation tools that might not automatically format JSON.
This is suitable for local developement. However, in production environments, it’s better to use a log management system (e.g., ELK, Splunk, DataDog) to parse the data into searchable fields. This is more efficient for large volumes and automated analysis.
Configuration files are the backbone of many applications, defining settings, database connections, API keys, and more. While many are manually written and thus already formatted, pretty-printing JSON becomes invaluable in scenarios:
The best and easiest way to indent JSON output in Python is by using the the indent
parameter in the json.dumps()
function.
import json
data = {"name": "Alice", "age": 30, "hobbies": ["reading", "chess", "hiking"]}
# Indent JSON output by 4 spaces
json_string = json.dumps(data, indent=4)
print(json_string)
json.dumps()
and pprint
?json.dumps()
converts Python objects (like a dict or list) to a JSON-formatted string. You can use json.dumps()
when you want to serialize Python data into a valid JSON string. pprint()
pretty-prints any Python data structure for readability; usually used for debugging or displaying nested Python objects in a readable format.
There are several tools to automatically pretty-print JSON in Python scripts. Here are a few options:
You can use json.tool
in the terminal to pretty-print JSON from a file or standard input:
python -m json.tool input.json
jq is another powerful and fast tool for formatting and querying JSON:
jq . input.json
You will have to first install jq
using the pip install jq
command.
Many editors like VS Code, PyCharm, and Sublime Text have built-in or plugin-based JSON formatters that you can use.
Pretty-printing JSON isn’t merely about making your JSON data look pretty; it’s a powerful technique to improve readability and enhance your debugging capabilities. With Python’s json.dumps()
and pprint
modules, you can quickly format output for better clarity. This extends beyond simple output, proving valuable for debugging API responses, logging structured data, and improving readability of config files. It’s a small change with a big impact on your development experience.
For more information on JSON, and working with files in Python, you can refer to the following tutorials:
Continue building with DigitalOcean Gen AI Platform.