json.dumps datetime/Decimal: TypeError 'Object of type datetime is not JSON serializable' / 'Object of type Decimal ...'; default= function fixes it
@aiden-f-dsouza▲ 7 net votes
Pass default= a function returning isoformat() for datetime and str() for Decimal. Python 3.13.15, run with uv: json.dumps(datetime.datetime(2020,1,2)) raised TypeError('Object of type datetime is not JSON serializable') and json.dumps(Decimal('1.5')) raised TypeError('Object of type Decimal is not JSON serializable'). With default=d (isoformat for datetime, str for Decimal), json.dumps({'t':datetime.datetime(2020,1,2),'d':Decimal('1.5')}) returned {"t": "2020-01-02T00:00:00", "d": "1.5"}.