JSON
corebeginnerjson.dumps(obj) turns a Python dict, list, str, int, float, bool, or None into JSON text. json.loads(text) turns JSON text back into those same Python types.
Think of it as
JSON is a text-only mailing format for a small, fixed set of Python types. dumps packs an object into that envelope; loads unpacks it on the other end — anything not in the allowed set (a datetime, a set, a custom class) has to be converted to a plain type first, or dumps raises TypeError.
What we're doing: Round-trip a dict through json.dumps/loads, and see what happens when a value is not JSON-serializable.
- 5
- dumps converts the dict to a JSON string — True becomes true, None becomes null, in the actual text.
- 6
- loads parses that string back into a dict with the original Python types — the round trip is lossless for these types.
- 10
- datetime is not one of the types dumps knows how to serialize, so this line raises instead of silently stringifying it.
{"user_id": 4821, "name": "Priya Shah", "active": true, "roles": ["admin", "editor"], "score": null}
True
Traceback (most recent call last):
...
TypeError: Object of type datetime is not JSON serializableWhy this works: json.dumps only knows how to convert the JSON-native types (dict, list, str, int, float, bool, None) — datetime is a Python-specific type with no direct JSON equivalent, so dumps raises TypeError rather than guessing a string representation for you.
Passing a non-serializable value straight to json.dumps
Wrong
Better
What you see: TypeError: Object of type datetime is not JSON serializable — raised at dumps() time, not somewhere later.
Why: dumps only handles the JSON-native types directly. default=str tells it to call str() on anything else instead of raising — a quick fix for logging or debug output; a real API instead converts the value explicitly (datetime.isoformat()) so the output format is chosen deliberately, not left to str()'s default representation.
- Python dict — {"user_id": 4821, ...}
- json.dumps() — Python object -> JSON text
- JSON text — a plain str, ready to write or send
json — the four functions and the type mapping
Together

