JSON in Python — Parse, Format & Generate
Python's built-in json module makes it straightforward to parse, generate, and manipulate JSON data. No third-party packages are required for most tasks.
Parse a JSON string
Use json.loads() to parse a JSON string into a Python dict or list. The 's' stands for string.
import json
json_string = '{"name": "Alice", "age": 30, "active": true}'
data = json.loads(json_string)
print(data["name"]) # Alice
print(data["age"]) # 30
print(type(data)) # <class 'dict'>Read a JSON file
Use json.load() (without 's') to parse a JSON file directly from a file object.
import json
with open("data.json", "r", encoding="utf-8") as f:
data = json.load(f)
print(data)Serialize Python objects to JSON
Use json.dumps() to convert a Python dict or list to a JSON string. Use indent for pretty-printing.
import json
data = {"name": "Alice", "scores": [95, 87, 92], "active": True}
# Compact
compact = json.dumps(data)
print(compact)
# {"name": "Alice", "scores": [95, 87, 92], "active": true}
# Pretty-printed
pretty = json.dumps(data, indent=2)
print(pretty)Write a JSON file
Use json.dump() to write Python data directly to a file.
import json
data = {"name": "Alice", "active": True}
with open("output.json", "w", encoding="utf-8") as f:
json.dump(data, f, indent=2)Handle JSON errors
Catch json.JSONDecodeError when parsing untrusted input.
import json
bad_json = '{"name": "Alice", missing_quote}'
try:
data = json.loads(bad_json)
except json.JSONDecodeError as e:
print(f"Parse error: {e.msg} at line {e.lineno}, col {e.colno}")Related Tools
JSON in Other Languages
Format and validate your JSON instantly
Free, no ads, no sign-up. Also converts JSON to TypeScript, YAML, CSV, and more.
Open JSON Formatter →