Question

How to Pretty-Print JSON in Python

pythonjsonformattingpretty-print

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 string
  • json.dump() writes a Python object as JSON directly to a file
  • json.loads() parses a JSON string into a Python object
  • json.load() reads JSON from a file into a Python object

The key idea is simple:

  1. Load the JSON data into Python
  2. 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() and json.loads() read JSON into Python
  • json.dump() and json.dumps() write Python data back into JSON

The s in loads and dumps means string.

So:

  • load / dump = file-based
  • loads / dumps = string-based
Take Quiz

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

import json

data = {
    "name": "Alice",
    "age": 30,
    "skills": ["Python", "SQL", "APIs"]
}

with open("output.json", "w") as file:
    json.dump(data, file, indent=4)

Pretty-printing an existing JSON file

import json

with open("input.json", "r") as file:
    data = json.load(file)

print(json.dumps(data, indent=4))

Sorting keys for more consistent output

import json

data = {
    "z": 1,
    "a": 2,
    "m": 3
}

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

This is useful when comparing files in version control or reading logs.

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:

  1. import json

    • Python loads the built-in JSON module.
  2. text = '{"user":"Sam","scores":[10,20],"admin":false}'

    • text is a JSON-formatted string.
    • It is still just text at this point.
  3. data = json.loads(text)

    • Python parses the JSON string.
    • data becomes a Python dictionary:
    {
        "user": "Sam",
        "scores": [10, 20],
        "admin": False
    }
    
  4. pretty = json.dumps(data, indent=2)

    • Python converts the dictionary back into a JSON string.
    • This time, it adds indentation and line breaks.
  5. print(pretty)

    • The formatted JSON is printed to the console.

Output:

{
  "user": "Sam",
  "scores": [
    10,
    20
  ],
  "admin": false
}

Notice that Python's False becomes JSON's false when converted back to JSON text.

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.

Take Quiz

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=4, sort_keys=True)

This makes output more consistent across runs.

Reading, modifying, and writing back

import json

with open("settings.json", "r") as file:
    settings = json.load(file)

settings["debug"] = False

with open("settings.json", "w") as file:
    json.dump(settings, file, indent=4)

This pattern is very common in scripts and tools that update JSON-based configs.

Error handling for invalid JSON

import json

try:
    with open("data.json", "r") as file:
        data = json.load(file)
except json.JSONDecodeError:
    print("The file does not contain valid JSON.")

Real code often includes this to avoid crashes from malformed input.

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:

import json

data = {"name": "Alice"}
result = json.dumps(data, indent=4)
print(result)

3. Forgetting to load file content first

Broken example:

import json

with open("data.json", "r") as file:
    print(json.dumps(file, indent=4))

Why this is wrong:

  • file is a file object, not parsed JSON data.

Correct approach:

import json

with open("data.json", "r") as file:
    data = json.load(file)

print(json.dumps(data, indent=4))

4. Trying to serialize unsupported data types

Broken example:

import json

data = {"numbers": {1, 2, 3}}
print(json.dumps(data, indent=4))

Why this fails:

  • A set is not directly JSON serializable.

Possible fix:

import json

data = {"numbers": [1, 2, 3]}
print(json.dumps(data, indent=4))

5. Expecting indent to parse invalid JSON

If the input JSON is malformed, pretty-printing will not fix it. The JSON must be valid before Python can parse it.

Comparisons

Here is a quick comparison of the most important JSON functions in Python:

FunctionInputOutputCommon use
json.loads()JSON stringPython objectParse JSON text from a string
json.load()File objectPython objectRead JSON from a file
json.dumps()Python objectJSON stringCreate formatted JSON text
json.dump()Python object + file objectWritten file contentSave JSON directly to a file

print(data) vs json.dumps(data, indent=4)

ApproachResultBest for
print(data)Python representationQuick debugging of Python objects
json.dumps(data, indent=4)Valid formatted JSON textReadable JSON output

Compact JSON vs pretty-printed JSON

StyleExample useTrade-off
CompactNetwork transferSmaller size, harder to read
Pretty-printedDebugging, config filesEasier to read, larger size
Take Quiz

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)

Remember

  • load / dump work with files
  • loads / dumps work with strings
  • indent adds readable formatting
  • sort_keys=True orders dictionary keys alphabetically
  • Python dict output is not the same as JSON text
  • JSON requires valid serializable data types

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.

json.dumps(data, indent=4, sort_keys=True)

Why am I getting TypeError: Object of type ... is not JSON serializable?

Your data contains a type that JSON does not support directly, such as a set or a custom object.

Can I use tabs or a different indentation size?

Yes. The indent argument controls the spacing. Common choices are 2 and 4.

Does pretty-printing change the actual data?

No. It only changes how the JSON text is formatted for readability.

Take Quiz

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 json module
  • 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
Take Quiz

Keep learning

Related questions

View more