runtime
469 / 500
question 469 Secure Python · medium

Make a record JSON-safe

Records leave the shop as JSON: order exports, webhook payloads, cache files. Instead of letting json.dumps fail deep inside a request, convert each record into plain JSON values first, explicitly, and refuse anything that has no agreed form.

Functionto_json_safe(value), nested to any depth
ConversionsDecimal → str; datetime and date → isoformat(); set/frozenset → sorted list; tuple → list; dicts and lists are converted item by item
Unchangedstr, int, float, bool and None
RaisesTypeError for a dict key that isn't a str, and for any other type (e.g. an object of your own class)
Rulethe input is not changed

Loading your progress…

Make a record JSON-safe — Python practice · Runtime