How do I pretty-print a JSON file in Python?

To pretty-print a JSON file in Python, use the built-in json module with the indent parameter. Here’s a step-by-step solution:

Method 1: Read and Pretty-Print a JSON File

import json

# Read JSON data from a file
with open("input.json", "r") as file:
    data = json.load(file)

# Convert to pretty-printed JSON string
pretty_json = json.dumps(data, indent=4, sort_keys=True)

# Print or save to a file
print(pretty_json)  # Display in console

# Save to a new file
with open("pretty_output.json", "w") as file:
    json.dump(data, file, indent=4, sort_keys=True)

Method 2: Pretty-Print a JSON String

If you already have a JSON string:

import json

json_string = '{"name": "Alice", "age": 30, "city": "Paris"}'
data = json.loads(json_string)  # Parse string to dict
pretty_json = json.dumps(data, indent=4)
print(pretty_json)

Key Parameters

ParameterDescription
indent=4Number of spaces for indentation (use None for compact format)
sort_keys=TrueSort keys alphabetically (optional)
ensure_ascii=FalseDisplay non-ASCII characters (e.g., é, ü) instead of escaping them

Example Output

Original JSON (input.json):

{"name": "Alice", "age": 30, "city": "Paris", "hobbies": ["coding", "hiking"]}

Pretty-Printed Result:

{
    "age": 30,
    "city": "Paris",
    "hobbies": [
        "coding",
        "hiking"
    ],
    "name": "Alice"
}

Bonus: Command-Line Method

Use Python’s json.tool module directly from the terminal:

# Pretty-print a JSON file
python -m json.tool input.json

# Save to a new file
python -m json.tool input.json > pretty_output.json

Common Issues & Fixes

  1. JSONDecodeError: Invalid JSON syntax. Validate your JSON first (e.g., JSONLint).
  2. Non-serializable objects: Use default=str in json.dumps() to handle non-serializable types (e.g., datetime).
  3. Unicode characters: Add ensure_ascii=False to preserve special characters.

This approach efficiently formats JSON for readability while maintaining compatibility with Python’s standard library.

Leave a Reply

Your email address will not be published. Required fields are marked *