JSON Pretty Print Using Python – With Examples



This content originally appeared on DEV Community and was authored by Pineapple

Working with JSON data is common in modern development, but minified JSON can be hard to read and debug. Python provides simple built-in tools to format JSON data in a readable way with proper indentation and structure.

What is JSON Pretty Print?

Pretty printing converts compact, minified JSON into a formatted structure with proper indentation, line breaks, and whitespace. This makes it much easier to understand the data structure, debug issues, and share with team members.

Why Pretty Print JSON?

  • Easy Debugging: Quickly identify structural issues and understand data relationships
  • Better Readability: Makes JSON data human-readable for code reviews and documentation
  • API Testing: Analyze API responses more efficiently
  • Configuration Files: Maintain readable config files that are easier to edit

The easiest way to pretty print JSON in Python is using json.dumps() with the indent parameter.

Example: Pretty Print a JSON String
import json

Minified JSON string
ugly_json = ‘{“firstname”:”James”,”surname”:”Bond”,”mobile”:[“007-700-007″,”001-007-007-0007”]}’

Parse JSON string to Python object
parsed = json.loads(ugly_json)

Pretty print with indentation
print(json.dumps(parsed, indent=4))

Output:
json{
“firstname”: “James”,
“surname”: “Bond”,
“mobile”: [
“007-700-007”,
“001-007-007-0007”
]
}

Read from File and Print
import json

Read JSON from file
with open(‘data.json’, ‘r’) as file:
data = json.load(file)

Pretty print to console
print(json.dumps(data, indent=4, sort_keys=True))

Write Pretty JSON to a File
import json

data = {
“users”: [
{“id”: 1, “name”: “John”, “role”: “Admin”},
{“id”: 2, “name”: “Jane”, “role”: “User”}
]
}

Write formatted JSON to file
with open(‘output.json’, ‘w’) as file:
json.dump(data, file, indent=4, sort_keys=True)

Understanding json.dumps() Parameters

indent
Specifies the number of spaces for indentation. Common values are 2 or 4.
sort_keys
Sorts dictionary keys alphabetically for consistent output.
ensure_ascii
By default, non-ASCII characters are escaped. Set to False to preserve them.

Pretty printing JSON in Python is straightforward with the built-in json module. Use json.dumps() with the indent parameter for formatted output, add sort_keys=True for consistency, and always handle exceptions when reading files. These simple techniques will make working with JSON data much easier in your development workflow.

Key Takeaways:

  • Use indent=4 for readable formatting
  • Add sort_keys=True for consistent output
  • Handle exceptions when reading JSON files
  • Use json.tool for quick command-line formatting
  • Create custom encoders for special data types like datetime

Or, you try using jsonformatter gg🚀


This content originally appeared on DEV Community and was authored by Pineapple