Format JSON in Python: Pretty Print, Indent, and Sort Keys

Last updated:

Python's built-in json module formats JSON with a single argument: json.dumps(data, indent=2) turns any dict or list into a readable, indented string. The python -m json.tool command ships with every Python 3.x installation — no pip install required — and formats a JSON file in one terminal command. Indent depth accepts any integer (2 and 4 are the most common), and the sort_keys=True flag orders output alphabetically, which cuts the diff noise on JSON stored in version control. This guide covers json.dumps() indent options, sort_keys, ensure_ascii, the python -m json.tool CLI, pretty-printing to a file with json.dump(), and custom separators for compact output.

Need to format a JSON snippet without writing code? Jsonic's JSON Formatter pretty prints and validates in one click.

Format JSON online

json.dumps with indent

The indent parameter of json.dumps controls indentation. Pass an integer for spaces, or a string (like '\t') for tabs.

import json

data = {
    "user": {"name": "Alice", "role": "admin"},
    "active": True,
    "tags": ["api", "internal"]
}

# 2-space indent (most common)
print(json.dumps(data, indent=2))

# Output:
# {
#   "user": {
#     "name": "Alice",
#     "role": "admin"
#   },
#   "active": true,
#   "tags": [
#     "api",
#     "internal"
#   ]
# }

python -m json.tool (command line)

The json.tool module formats a JSON file or stdin output without writing a script. It is built into Python — no installation required.

# Format a file and print to stdout
python3 -m json.tool input.json

# Format a file and save the result
python3 -m json.tool input.json output.json

# Format JSON from a curl response
curl -s https://api.example.com/data | python3 -m json.tool

# Format JSON passed as a string
echo '{"name":"Alice","active":true}' | python3 -m json.tool

json.tool uses 4-space indentation by default. Pass --indent 2 to change it (Python 3.9+):

python3 -m json.tool --indent 2 input.json

Sort keys alphabetically

Pass sort_keys=True to sort all object keys alphabetically at every nesting level. Useful for consistent diffs and canonical output.

import json

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

print(json.dumps(data, indent=2, sort_keys=True))
# {
#   "a": 1,
#   "m": 2,
#   "z": 3
# }

From the command line: python3 -m json.tool --sort-keys input.json

Format and write to a file

import json

data = {"user": {"name": "Alice"}, "active": True}

with open("output.json", "w") as f:
    json.dump(data, f, indent=2)
    # Note: json.dump (not json.dumps) writes directly to a file object

Use json.dump (no trailing s) to write directly to a file object. Use json.dumps to get a formatted string.

Format a JSON API response

import json
import urllib.request

url = "https://api.example.com/users"
with urllib.request.urlopen(url) as response:
    data = json.load(response)

# Pretty print the parsed response
print(json.dumps(data, indent=2))

If you use the requests library, call response.json() first, then pass the result to json.dumps:

import json
import requests

response = requests.get("https://api.example.com/users")
data = response.json()
print(json.dumps(data, indent=2))

Compact output (minify)

To produce the most compact JSON — no spaces after separators — pass separators=(',', ':'):

import json

data = {"name": "Alice", "active": True}

# Compact (minified)
print(json.dumps(data, separators=(',', ':')))
# {"name":"Alice","active":true}

# Default (slight spacing)
print(json.dumps(data))
# {"name": "Alice", "active": true}

Frequently asked questions

How do I pretty print JSON in Python?

Use json.dumps(data, indent=2). The indent argument sets the number of spaces per nesting level. 2 and 4 are the most common values. For tabs use indent='\t'. Use json.dump(data, file, indent=2) to write directly to a file.

What is the difference between json.dump and json.dumps?

json.dumps returns a formatted string. json.dump writes directly to a file object passed as its second argument. Both accept the same indent, sort_keys, and separators arguments. Use json.dumps when you need the string in memory; use json.dump when writing to a file.

How do I format a JSON file from the terminal?

Run python3 -m json.tool input.json. This reads the file, validates the JSON, and prints the formatted output to stdout with 4-space indentation. Redirect with {'>'} output.json to save it. Use --indent 2 (Python 3.9+) for 2-space indentation.

Does json.dumps preserve key order?

Yes. Since Python 3.7, dictionaries preserve insertion order, and json.dumps outputs keys in the same order unless you pass sort_keys=True.

How do I sort JSON keys in Python?

Pass sort_keys=True to json.dumps: json.dumps(data, indent=2, sort_keys=True). This sorts all object keys alphabetically at every nesting level. From the command line: python3 -m json.tool --sort-keys input.json.

How do I handle non-serializable types like datetime?

Pass default=str to json.dumps to convert non-serializable values to strings: json.dumps(data, indent=2, default=str). For datetime objects this produces ISO 8601 strings. For custom types, subclass json.JSONEncoder and override default().

Format JSON without writing code

For a quick paste-and-format without opening a terminal, Jsonic's JSON Formatter pretty prints, validates, and lets you copy the result in one step.

Open JSON Formatter