Languages Knowledge Base

Working with JSON in Python: Complete Developer Guide

Master JSON in Python: json.loads(), json.dumps(), pretty printing with indent=2, custom encoders, and validating JSON payloads in Python 3.

In Python, use json.loads(text) to parse a JSON string into a dict and json.dumps(obj, indent=2) to serialize it back to a pretty-printed JSON string. The built-in json module requires no installation.

The Python json Module

Python ships with a built-in json module. No third-party library is required to parse or generate JSON in Python 3.

Core Functions:

  • json.loads(string) — Parse a JSON string into a Python dict or list.
  • json.dumps(obj) — Serialize a Python object to a JSON string.
  • json.load(file) — Parse JSON directly from an open file object.
  • json.dump(obj, file) — Write JSON directly to an open file object.

Pretty Printing JSON in Python

Pass indent=2 or indent=4 to json.dumps() for human-readable output. Add sort_keys=True for alphabetically ordered keys.

Validating JSON in Python

Wrap json.loads() in a try/except block to catch json.JSONDecodeError syntax errors:

json
import json

# Parse JSON string
payload = '{"name": "Alice", "score": 99, "active": true}'
data = json.loads(payload)
print(data["name"])  # Alice

# Pretty print JSON
pretty = json.dumps(data, indent=2, sort_keys=True)
print(pretty)

# Validate JSON safely
def is_valid_json(text: str) -> bool:
    try:
        json.loads(text)
        return True
    except json.JSONDecodeError:
        return False

# Read/Write JSON files
with open("data.json", "r") as f:
    obj = json.load(f)

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

Try the free JSON Formatter

Runs entirely in your browser — no upload, no signup, and your data never leaves your device.

Open JSON Formatter

Frequently Asked Questions

How do I pretty print JSON in Python?

Pass indent=2 or indent=4 to json.dumps(). Example: json.dumps(data, indent=2).

How do I parse a JSON string in Python?

Use json.loads(text) to convert a JSON string into a Python dict or list.

How do I handle JSON decode errors in Python?

Wrap json.loads() in a try/except json.JSONDecodeError block.

Does Python support trailing commas or comments in JSON?

No. Python's json module strictly follows RFC 8259, which forbids trailing commas and comments.

Related JSON Topics & Reference Articles