How to read and write JSON
Understand the mapping
JSON objects become dictionaries, arrays become lists, and JSON strings, numbers, booleans, and null map to their Python counterparts.
import json
text = '{"name": "Ada", "active": true, "skills": ["math", "code"]}'
data = json.loads(text)
print(data["name"])
print(data["skills"][0])
Write JSON text
dumps() returns a string. Indentation makes it readable; sort_keys gives stable key order for display.
import json
record = {"score": 95, "name": "Ada", "active": True}
text = json.dumps(record, indent=2, sort_keys=True)
print(text)
Read and write files
load() and dump() work with file objects. Use UTF-8 and a with statement.
import json
settings = {"theme": "dark", "font_size": 16}
with open("settings.json", "w", encoding="utf-8") as file:
json.dump(settings, file, indent=2)
with open("settings.json", encoding="utf-8") as file:
loaded = json.load(file)
print(loaded["theme"])
Handle invalid or unsupported data
Malformed input raises JSONDecodeError. Objects such as sets and dates are not JSON serializable until converted to supported values.
import json
try:
json.loads("{bad json}")
except json.JSONDecodeError as error:
print(f"Invalid JSON at line {error.lineno}, column {error.colno}")