How to Parse JSON in Python

← All guides

Python ships with the json module in the standard library. Use json.loads/json.load to parse and json.dumps/json.dump to serialize.

Parse a JSON string

json.loads (load string) parses JSON text into Python dicts, lists, and scalars.

python
import json

text = '{"name": "Ada", "roles": ["admin", "dev"]}'
data = json.loads(text)
print(data["name"])       # Ada
print(data["roles"][0])   # admin

Read JSON from a file

json.load reads directly from a file object.

python
import json

with open("data.json", encoding="utf-8") as f:
    data = json.load(f)

Serialize to JSON

json.dumps returns a string; use indent to pretty-print and sort_keys for stable output. Set ensure_ascii=False to keep Unicode readable.

python
import json

obj = {"name": "Ada", "active": True}
print(json.dumps(obj))                                  # compact
print(json.dumps(obj, indent=2, sort_keys=True,
                 ensure_ascii=False))                  # pretty

Handle invalid JSON

Invalid input raises json.JSONDecodeError, which includes the line and column of the problem.

python
import json

try:
    data = json.loads(text)
except json.JSONDecodeError as e:
    print(f"Invalid JSON at line {e.lineno}, col {e.colno}: {e.msg}")

Frequently Asked Questions

json.loads parses a string ('s' for string); json.load reads and parses from a file-like object. The same distinction applies to json.dumps and json.dump.

Pass ensure_ascii=False to json.dumps so characters like accents and emoji are written directly instead of \u escapes.

Use the JSON to Python tool to generate dataclasses, TypedDicts or Pydantic models from a sample JSON document.

Related Tools