Fix "Object of type datetime is not JSON serializable"
Object of type datetime is not JSON serializable is Python's json module refusing your data. Learn the default= escape hatch, custom JSONEncoder subclasses, dataclasses, and object_hook decoding.
You built a nice dictionary, called json.dumps() on it, and got slapped with this: TypeError: Object of type datetime is not JSON serializable It's one of Python's most-Googled tracebacks, and the message is blunt but honest: the json module only speaks a small set of types — dict , list , str , int , float , bool , and None . Everything else — datetime , Decimal , set , your dataclasses, your custom classes — needs a translator. This tutorial builds that translator four ways, from the 30-second fix to the reusable pattern. What you'll learn The four json functions and how dump vs dumps differ Why datetime (and Decimal , set , dataclasses) break json.dumps The default= escape hatch for one-off serialization How to write a custom JSONEncoder subclass you can reuse everywhere Serializing dataclasses with asdict Decoding back into real objects with object_hook Pretty-printing JSON with indent Step 1 — The four functions: json dump vs dumps The json module has four functions, and the naming is the whole API: import json payload = {"name": "Hasnain", "tags": ["python", "json"], "active": True} text = json.dumps(payload) # dumps = "dump string": Python object -> str back = json.loads(text) # loads = "load string": str -> Python object print(text) print(type(text), type(back)) The other two work with files instead of strings: import json payload = {"name": "Hasnain", "tags": ["python", "json"], "active": True} with open("/tmp/payload.json", "w", encoding="utf-8") as f: json.dump(payload, f) # dump: Python object -> file object with open("/tmp/payload.json", encoding="utf-8") as f: back = json.load(f) # load: file object -> Python object print(back) Memory aid: the trailing s means string . dumps / loads for strings, dump / load for files. That distinction…