Python's built-in json module handles JSON serialization and deserialization. Python dict/list/str/int/float/bool/None map directly to JSON object/array/string/number/boolean/null.
| Item | Syntax / Value | Description |
|---|---|---|
| json.loads | json.loads(s, *, cls=None, object_hook=None, ...) → obj | Parse JSON string to Python object |
| json.dumps | json.dumps(obj, *, indent=None, sort_keys=False, ...) → str | Serialize Python object to JSON string |
| json.load | json.load(fp) → obj | Parse JSON from file object |
| json.dump | json.dump(obj, fp, *, indent=None, ...) | Serialize Python object to file |
| indent | json.dumps(obj, indent=2) | Pretty-print with indentation |
| sort_keys | json.dumps(obj, sort_keys=True) | Sort object keys alphabetically |
| ensure_ascii | json.dumps(obj, ensure_ascii=False) | Allow non-ASCII Unicode in output |
| default | json.dumps(obj, default=str) | Function for objects not serializable by default |
| object_hook | json.loads(s, object_hook=fn) | fn called for each JSON object during parsing |
| separators | json.dumps(obj, separators=(',',':')) | Compact output — remove spaces |
| JSONDecodeError | except json.JSONDecodeError as e: | Exception for invalid JSON |
| Type mapping: dict → object | {'key':'value'} ↔ {"key":"value"} | Python dict maps to JSON object |
| Type mapping: list → array | [1,2,3] ↔ [1,2,3] | Python list maps to JSON array |
| Type mapping: str | 'hello' ↔ "hello" | Python str maps to JSON string |
| Type mapping: int/float | 42, 3.14 ↔ 42, 3.14 | Python numbers map to JSON numbers |
| Type mapping: bool | True/False ↔ true/false | Python bool maps to JSON boolean |
| Type mapping: None | None ↔ null | Python None maps to JSON null |
| Custom encoder | class MyEncoder(json.JSONEncoder): def default(self,o): ... | Handle custom types |
| Custom decoder | json.loads(s, object_hook=lambda d: MyClass(**d)) | Convert dict to custom class |
import json
from datetime import datetime, date
from pathlib import Path
# ── 1. Basic parse and dump ───────────────────────────────────
data = {
"name": "Alice",
"score": 95,
"grades": [95, 87, 92, 98],
"active": True,
"notes": None,
"metadata": {"created": "2026-06-25", "version": 3}
}
json_str = json.dumps(data, indent=2, ensure_ascii=False)
print(json_str)
parsed = json.loads(json_str)
print(f"Name: {parsed['name']}, Score: {parsed['score']}")
# ── 2. File I/O ───────────────────────────────────────────────
Path("student.json").write_text(json_str)
with open("student.json") as f:
loaded = json.load(f)
print("Loaded from file:", loaded["name"])
# ── 3. Custom encoder — handle dates ──────────────────────────
class DateEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, (datetime, date)):
return obj.isoformat()
return super().default(obj)
event = {"name": "Graduation", "date": date(2026, 6, 15), "time": datetime.now()}
print(json.dumps(event, cls=DateEncoder, indent=2))
# ── 4. Custom decoder ─────────────────────────────────────────
class Student:
def __init__(self, name, score): self.name = name; self.score = score
def __repr__(self): return f"Student({self.name!r}, {self.score})"
students_json = '[{"name":"Alice","score":95},{"name":"Bob","score":87}]'
students = json.loads(students_json, object_hook=lambda d: Student(**d))
print(students)
# ── 5. Error handling ─────────────────────────────────────────
for s in ['{"valid":true}', 'not json', '{bad:json}', '{"trailing":1,}']:
try:
obj = json.loads(s)
print(f" ✅ Parsed: {obj}")
except json.JSONDecodeError as e:
print(f" ❌ Error at line {e.lineno}: {e.msg}")
# ── 6. Pretty print any JSON ──────────────────────────────────
raw = '[{"id":1,"name":"Alice"},{"id":2,"name":"Bob"}]'
print(json.dumps(json.loads(raw), indent=2, sort_keys=True))
# Cleanup
Path("student.json").unlink(missing_ok=True)
# python3 json_demo.py