object_hook Decoder
Pass object_hook to json.loads() to transform parsed dicts into custom objects during decoding.
Pass object_hook to json.loads() to transform parsed dicts into custom objects during decoding.
import json
from datetime import datetime
def decode_user(d):
if "created_at" in d:
d["created_at"] = datetime.fromisoformat(d["created_at"])
return d
payload = '{"name":"Alice","created_at":"2024-06-15T14:30:00"}'
user = json.loads(payload, object_hook=decode_user)
print(type(user["created_at"])) # datetime
object_hook is called for every nested dict — check keys to avoid unintended conversion.