`json` — JSON Encoding and Decoding
Python · Standard Library · Run with python3
Explanation
`json.dumps()` serializes Python objects to JSON strings; `json.loads()` parses JSON strings. `json.dump()` / `json.load()` work with file objects. The `default` parameter of `dumps` handles non-serializable types (e.g., `datetime`). `object_hook` in `loads` transforms decoded dicts. `indent` pretty-prints; `sort_keys` ensures deterministic output for diffs.
Real-World Scenario
A REST API endpoint receives a JSON body, processes it, and returns a JSON response. `json.loads(request.body)` parses the input; `json.dumps(result, default=str)` serializes the response — `default=str` handles `datetime`, `Decimal`, and other non-standard types by falling back to their string representation. ```python import json from datetime import datetime from dataclasses import dataclass, asdict @dataclass class Event: name: str timestamp: datetime tags: list[str] def serialize(obj): if isinstance(obj, datetime): return obj.isoformat() raise TypeError(f"Not serializable: {type(obj)}") event = Event("deploy", datetime(2024, 3, 15, 10, 30), ["prod", "v2.1"]) payload = asdict(event) # Serialize with custom handler json_str = json.dumps(payload, default=serialize, indent=2) print(json_str) # Parse back data = json.loads(json_str) print(data["timestamp"]) # "2024-03-15T10:30:00" ```
Quick Snippet
import json
from datetime import datetime
from dataclasses import dataclass, asdict
@dataclass
class Event:
name: str
timestamp: datetime
tags: list[str]
def serialize(obj):
if isinstance(obj, datetime):
return obj.isoformat()
raise TypeError(f"Not serializable: {type(obj)}")
event = Event("deploy", datetime(2024, 3, 15, 10, 30), ["prod", "v2.1"])
payload = asdict(event)
# Serialize with custom handler
json_str = json.dumps(payload, default=serialize, indent=2)
print(json_str)
# Parse back
data = json.loads(json_str)
print(data["timestamp"]) # "2024-03-15T10:30:00"Full Example
# Compile: python3 json_basics.py
# Output:
# 2024-03-15T10:30:00
import json
from datetime import datetime
from dataclasses import dataclass, asdict
@dataclass
class Event:
name: str
timestamp: datetime
tags: list[str]
def serialize(obj):
if isinstance(obj, datetime):
return obj.isoformat()
raise TypeError(f"Not serializable: {type(obj)}")
event = Event("deploy", datetime(2024, 3, 15, 10, 30), ["prod", "v2.1"])
payload = asdict(event)
json_str = json.dumps(payload, default=serialize, indent=2)
print(json_str)
data = json.loads(json_str)
print(data["timestamp"])
# Pretty-print sorted keys
config = {"z_last": 3, "a_first": 1, "m_middle": 2}
print(json.dumps(config, sort_keys=True))
# Nested structures round-trip
nested = {"users": [{"id": 1, "active": True}, {"id": 2, "active": False}]}
assert json.loads(json.dumps(nested)) == nested
print("Round-trip: OK")
python3 json_basics.py