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.
Function
to_json_safe(value), nested to any depthConversions
Decimal → str; datetime and date → isoformat(); set/frozenset → sorted list; tuple → list; dicts and lists are converted item by itemUnchanged
str, int, float, bool and NoneRaises
TypeError 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