Skip to content

How to Pretty Print JSON in Python

Learn how to format JSON data with proper indentation, line breaks, and spacing in Python using json.dumps(), json.dump(), and command-line tools for debugging and readability.

When working with JSON data in Python, the default output is a compact, single-line format that is efficient for machines but difficult for humans to read. Pretty printing formats JSON with proper indentation, line breaks, and spacing: making it much easier to inspect, debug, and understand complex data structures.

Python's built-in json module provides everything you need to pretty print JSON data from strings, dictionaries, files, and API responses.

Basic Pretty Printing With json.dumps()

The json.dumps() function converts a Python object to a JSON-formatted string. The indent parameter controls the indentation level:

import json

data = {
    "name": "Tom",
    "age": 28,
    "designation": "Software Engineer",
    "skills": ["Python", "JavaScript", "SQL"]
}

print(json.dumps(data))

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

Output:

{"name": "Tom", "age": 28, "designation": "Software Engineer", "skills": ["Python", "JavaScript", "SQL"]}
{
  "name": "Tom",
  "age": 28,
  "designation": "Software Engineer",
  "skills": [
    "Python",
    "JavaScript",
    "SQL"
  ]
}

Pretty Printing a JSON String

When you receive JSON as a string (e.g., from an API), parse it first with json.loads(), then format it with json.dumps():

import json

json_string = '[{"Employee ID":1,"Name":"Tom","Designation":"Software Engineer"},{"Employee ID":2,"Name":"Garima","Designation":"Email Marketing Specialist"}]'

data = json.loads(json_string)

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

Output:

[
  {
    "Employee ID": 1,
    "Name": "Tom",
    "Designation": "Software Engineer"
  },
  {
    "Employee ID": 2,
    "Name": "Garima",
    "Designation": "Email Marketing Specialist"
  }
]

Pretty Printing JSON From a File

To pretty print JSON data stored in a file, load it with json.load() and format with json.dumps():

import json

with open('myfile.json', 'r') as f:
    data = json.load(f)

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

Output:

{
  "emp1": {
    "name": "Lisa",
    "designation": "programmer",
    "age": "34",
    "salary": "54000"
  },
  "emp2": {
    "name": "Elis",
    "designation": "Trainee",
    "age": "24",
    "salary": "40000"
  }
}

Controlling the Output Format

json.dumps() provides several parameters to customize the output:

Sorting Keys

Use sort_keys=True to sort dictionary keys alphabetically:

import json

data = {"zebra": 1, "apple": 2, "mango": 3}

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

Output:

{
  "apple": 2,
  "mango": 3,
  "zebra": 1
}

Custom Separators

The separators parameter controls the characters used between items and between keys and values:

import json

data = {"name": "Alice", "age": 30}

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

print(json.dumps(data, separators=(',', ':')))

Output:

{
  "name": "Alice",
  "age": 30
}
{"name":"Alice","age":30}

Handling Non-ASCII Characters

Use ensure_ascii=False to preserve Unicode characters instead of escaping them:

import json

data = {"city": "München", "country": "日本"}

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

print(json.dumps(data, indent=2, ensure_ascii=False))

Output:

{
  "city": "M\u00fcnchen",
  "country": "\u65e5\u672c"
}
{
  "city": "München",
  "country": "日本"
}

Parameter Quick Reference

Parameter Description Default Example
indent Number of spaces per indentation level None (compact) indent=2
sort_keys Sort dictionary keys alphabetically False sort_keys=True
separators Custom item and key-value separators (', ', ': ') separators=(',', ':')
ensure_ascii Escape non-ASCII characters True ensure_ascii=False
default Function to handle non-serializable objects None default=str

Using pprint as an Alternative

Python's pprint module can also format data structures, but it produces Python-specific output (not valid JSON):

import pprint
import json

data = {"name": "Alice", "skills": ["Python", "SQL"], "active": True}

pprint.pprint(data)

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

Output:

{'active': True, 'name': 'Alice', 'skills': ['Python', 'SQL']}
{
  "name": "Alice",
  "skills": [
    "Python",
    "SQL"
  ],
  "active": true
}

Pretty Printing API Responses

A common use case is formatting JSON responses from web APIs:

import json
import urllib.request

url = "https://jsonplaceholder.typicode.com/users/1"

with urllib.request.urlopen(url) as response:
    data = json.loads(response.read())

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

Output:

{
  "id": 1,
  "name": "Leanne Graham",
  "username": "Bret",
  "email": "Sincere@april.biz",
  "address": {
    "street": "Kulas Light",
    "suite": "Apt. 556",
    "city": "Gwenborough",
    "zipcode": "92998-3874",
    "geo": {
      "lat": "-37.3159",
      "lng": "81.1496"
    }
  },
  "phone": "1-770-736-8031 x56442",
  "website": "hildegard.org",
  "company": {
    "name": "Romaguera-Crona",
    "catchPhrase": "Multi-layered client-server neural-net",
    "bs": "harness real-time e-markets"
  }
}

Saving Pretty Printed JSON to a File

To write formatted JSON to a file, use json.dump() with the indent parameter:

import json

data = {
    "employees": [
        {"name": "Alice", "role": "Developer"},
        {"name": "Bob", "role": "Designer"}
    ]
}

with open('output.json', 'w') as f:
    json.dump(data, f, indent=2)

print("Pretty printed JSON saved to output.json")

Command-Line Pretty Printing

Python can pretty print JSON directly from the command line without writing a script:

python -m json.tool myfile.json

echo '{"name":"Alice","age":30}' | python -m json.tool

python -m json.tool --sort-keys myfile.json

Output:

{
    "age": 30,
    "name": "Alice"
}

Handling Non-Serializable Objects

json.dumps() only handles basic Python types by default. For custom objects, use the default parameter:

import json
from datetime import datetime

data = {
    "event": "Launch",
    "timestamp": datetime.now()
}


print(json.dumps(data, indent=2, default=str))

Output:

{
  "event": "Launch",
  "timestamp": "2024-01-15 14:30:00.123456"
}

Conclusion

Pretty printing JSON in Python is straightforward with the built-in json module.

  • Use json.dumps(data, indent=2) for formatted string output
  • Use json.dump(data, file, indent=2) for writing to files
  • Use python -m json.tool for quick command-line formatting.

Customize the output with sort_keys for alphabetical ordering, ensure_ascii=False for Unicode preservation, and default=str for handling non-serializable objects. Pretty printing is invaluable for debugging, logging, and making JSON data human-readable.

Navigation