Tutorial

How to Pretty Print JSON in Python

How to Pretty Print JSON in Python

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.

1. Python Pretty Print JSON String

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"
  }
]
  • First, we use json.loads() to create the JSON object from the JSON string.
  • The json.dumps() method takes the JSON object and returns a JSON formatted string. The indent parameter defines the indent level for the formatted string.

2. Python Pretty Print JSON File

Let’s see what happens when we try to print a JSON file data. The file data is saved in a pretty printed format.

Json Pretty Printed File
Json Pretty Printed File
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.

Debugging API responses

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.

Logging structured data

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.

Improving readability of config files

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:

  • When a script or application generates or modifies a JSON config file, it might save it in a minified format. Pretty-printing ensures that the saved file is human-readable for subsequent manual edits or review.
  • If you receive a JSON config file from an external source, pretty-printing it can quickly reveal its structure and content, making it easier to validate against expectations.
  • When changes are made to a JSON config file, pretty-printing with consistent indentation (and optionally sorted keys) ensures that diffs in version control systems (like Git) are clean and meaningful, showing only the actual content changes rather than formatting shifts.

FAQs

1. What’s the best way to indent JSON output in Python?

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)

2. What’s the difference between 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.

3. Is there a tool to automatically pretty print JSON in Python scripts?

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.

Conclusion

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:

References

Continue building with DigitalOcean Gen AI Platform.

About the author(s)

Pankaj Kumar
Pankaj Kumar
See author profile
Category:
Tutorial

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

Become a contributor for community

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

DigitalOcean Documentation

Full documentation for every DigitalOcean product.

Resources for startups and SMBs

The Wave has everything you need to know about building a business, from raising funding to marketing your product.

Get our newsletter

Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

New accounts only. By submitting your email you agree to our Privacy Policy

The developer cloud

Scale up as you grow — whether you're running one virtual machine or ten thousand.

Get started for free

Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

*This promotional offer applies to new accounts only.