Serialize Dates with a default Hook

Hard ⏱ 18 min 27% acceptance ★★★★★ 4.5
json.dumps({'day': date(2026, 7, 28)}) raises TypeError — dates aren't JSON. Write dump_with_dates(obj) passing a default= function that converts date/datetime values to their isoformat() strings and raises TypeError for anything else unknown.

Examples

Example 1
Input
dump_with_dates({'day': date(2026, 7, 28)})
Output
{"day": "2026-07-28"}
Explanation

The hook translated the unserializable value.

Constraints

  • Use the default= parameter, not pre-conversion.
  • Unknown types still raise TypeError.

Topics

JSONcustom serialization

Companies

StripePlaidSquare

Hints

Hint 1

def encode(o): if isinstance(o, (date, datetime)): return o.isoformat().

Hint 2

Re-raise TypeError otherwise — dumps expects that.

Loading the Python runtime… Run executes your code and shows printed output; Submit checks your function against this problem's examples.