Question
How can I pretty-print a JSON file in Python so that the output is easier for humans to read?
Short Answer
By the end of this page, you will understand how to format JSON nicely in Python using the built-in json module. You will learn how to print JSON with indentation, how to write formatted JSON to a file, and how to avoid common mistakes when working with Python dictionaries and JSON text.
Concept
JSON is a text format used to store and exchange structured data. In Python, JSON data is commonly converted into dictionaries, lists, strings, numbers, booleans, and None.
Pretty-printing JSON means formatting it with:
- indentation
- line breaks
- readable spacing
- optionally sorted keys
This matters because compact JSON is hard to read during debugging, logging, testing, and configuration editing.
In Python, the built-in json module provides the main tools for this:
json.dumps()converts a Python object to a JSON stringjson.dump()writes a Python object as JSON directly to a filejson.loads()parses a JSON string into a Python objectjson.load()reads JSON from a file into a Python object
The key idea is simple:
- Load the JSON data into Python
- Output it again with formatting options such as
indent=4
A common point of confusion is that Python objects are not automatically JSON text. A Python dictionary may look similar to JSON, but JSON requires double quotes and follows JSON-specific formatting rules. The json module handles those differences for you.
Mental Model
Think of JSON as a messy paragraph and pretty-printing as adding punctuation, line breaks, and indentation so a person can scan it easily.
- Raw JSON: everything is squeezed together
- Pretty-printed JSON: each nested level is visually grouped
Another way to think about it:
json.load()andjson.loads()read JSON into Pythonjson.dump()andjson.dumps()write Python data back into JSON
The s in loads and dumps means string.
So:
load/dump= file-basedloads/dumps= string-based
Syntax and Examples
The most common way to pretty-print JSON in Python is to use json.dumps() with the indent argument.
import json
data = {
"name": "Alice",
"age": 30,
"skills": ["Python", "SQL", "APIs"],
"active": True
}
pretty_json = json.dumps(data, indent=4)
print(pretty_json)
Output:
{
"name": "Alice",
"age": 30,
"skills": [
"Python",
"SQL",
"APIs"
],
"active": true
}
Writing pretty JSON to a file
Step by Step Execution
Consider this example:
import json
text = '{"user":"Sam","scores":[10,20],"admin":false}'
data = json.loads(text)
pretty = json.dumps(data, indent=2)
print(pretty)
Step by step:
-
import json- Python loads the built-in JSON module.
-
text = '{"user":"Sam","scores":[10,20],"admin":false}'textis a JSON-formatted string.- It is still just text at this point.
-
data = json.loads(text)- Python parses the JSON string.
databecomes a Python dictionary:
{ "user": "Sam", "scores": [10, 20], "admin": False } -
pretty = json.dumps(data, indent=2)- Python converts the dictionary back into a JSON string.
Real World Use Cases
Pretty-printing JSON is useful in many real programming tasks:
-
Debugging API responses
- When an API returns nested data, formatted JSON is much easier to inspect.
-
Writing configuration files
- Human-edited config files should be readable.
-
Saving structured application data
- Logs, exported settings, or cached responses are easier to review when formatted.
-
Testing and development
- Pretty output helps verify that a program generated the correct structure.
-
Version control
- Cleanly formatted JSON is easier to compare in Git diffs.
Example: pretty-printing an API response
import json
import urllib.request
with urllib.request.urlopen("https://api.example.com/data") as response:
data = json.load(response)
print(json.dumps(data, indent=4))
In practice, the exact API URL will vary, but the formatting approach stays the same.
Real Codebase Usage
In real projects, developers often combine pretty-printing with a few common patterns.
Validation before writing
Make sure the data can actually be serialized to JSON.
import json
config = {"theme": "dark", "timeout": 30}
json_text = json.dumps(config, indent=4)
If the object contains unsupported types such as a set, serialization will fail.
Logging readable payloads
import json
payload = {"event": "login", "user": "alice", "success": True}
print(json.dumps(payload, indent=2))
Writing stable output with sorted keys
import json
settings = {"port": 8080, "debug": True, "host": "localhost"}
with open("settings.json", "w") as file:
json.dump(settings, file, indent=, sort_keys=)
Common Mistakes
Here are common mistakes beginners make when pretty-printing JSON in Python.
1. Confusing Python dictionaries with JSON strings
Broken example:
data = {'name': 'Alice', 'age': 30}
print(data)
Why this is a problem:
- This prints a Python dictionary representation, not proper JSON.
- Python may use single quotes, which are not valid JSON.
Correct approach:
import json
data = {'name': 'Alice', 'age': 30}
print(json.dumps(data, indent=4))
2. Using dump() when you wanted dumps()
Broken example:
import json
data = {"name": "Alice"}
result = json.dump(data)
Why this is wrong:
json.dump()writes to a file object.- It does not return the JSON string you want.
Correct approach:
Comparisons
Here is a quick comparison of the most important JSON functions in Python:
| Function | Input | Output | Common use |
|---|---|---|---|
json.loads() | JSON string | Python object | Parse JSON text from a string |
json.load() | File object | Python object | Read JSON from a file |
json.dumps() | Python object | JSON string | Create formatted JSON text |
json.dump() | Python object + file object | Written file content | Save JSON directly to a file |
print(data) vs json.dumps(data, indent=4)
Cheat Sheet
import json
Parse JSON
json.loads(text) # string -> Python object
json.load(file) # file -> Python object
Create JSON
json.dumps(data) # Python object -> JSON string
json.dumps(data, indent=4) # pretty JSON string
json.dumps(data, sort_keys=True) # sorted keys
json.dump(data, file, indent=4) # write pretty JSON to file
Most useful pretty-print pattern
import json
with open("data.json", "r") as file:
data = json.load(file)
print(json.dumps(data, indent=4))
Write formatted JSON to a file
with open("output.json", "w") as file:
json.dump(data, file, indent=4)
FAQ
How do I pretty-print JSON in Python?
Use json.dumps(data, indent=4) to create formatted JSON text from a Python object.
How do I pretty-print a JSON file in Python?
Read it with json.load() and then print it with json.dumps(..., indent=4).
import json
with open("data.json") as file:
data = json.load(file)
print(json.dumps(data, indent=4))
What is the difference between json.dump() and json.dumps()?
json.dump() writes JSON directly to a file. json.dumps() returns a JSON string.
Why does Python print single quotes instead of double quotes?
Because print(my_dict) shows a Python dictionary representation, not JSON. Use json.dumps() to get proper JSON formatting.
Can I sort keys when pretty-printing JSON?
Yes. Use sort_keys=True.
Mini Project
Description
Build a small Python script that reads a compact JSON file, pretty-prints it to the terminal, and saves a formatted copy to a new file. This demonstrates the full workflow of reading, parsing, formatting, and writing JSON in a practical way.
Goal
Create a script that turns unreadable JSON into a clean, indented JSON file and also displays it in the console.
Requirements
- Read JSON data from an input file named
input.json - Parse the file contents safely using Python's
jsonmodule - Print the JSON to the terminal with indentation
- Save the formatted JSON to a new file named
pretty_output.json - Handle invalid JSON gracefully with an error message
Keep learning
Related questions
@staticmethod vs @classmethod in Python Explained
Learn the difference between @staticmethod and @classmethod in Python with clear examples, use cases, mistakes, and a mini project.
Call a Function by Name in a Python Module
Learn how to call a function by name in a Python module using strings, getattr, and safe patterns for dynamic function dispatch.
Catch Multiple Exceptions in One except Block in Python
Learn how to catch multiple exceptions in one Python except block using tuples, with examples, mistakes, and real-world usage.