How to Parse JSON in Python
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]) # adminRead 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)) # prettyHandle 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}")