sethserver / Python

TypeError: Object is not JSON serializable - Python JSON Encoding Fix

By Seth Black Updated September 27, 2024

The JSON serializable error usually rears its ugly head after you've already deployed to production and likes to attack Decimal (TypeError: Object of type Decimal is not JSON serializable) and datetime (TypeError: Object of type datetime is not JSON serializable) variables tucked comfortably inside of dictionaries. Here's a few quick examples from the Python3 REPL.

>>> import json >>> import decimal >>> u = decimal.Decimal(42342.23) >>> json.dumps({'value': u}) TypeError: Object of type Decimal is not JSON serializable >>> import datetime >>> v = datetime.datetime(2020, 1, 1) >>> json.dumps({'value': v}) TypeError: Object of type datetime is not JSON serializable

Python3 makes it very simple to quickly hack around this error using f-strings and the default parameter.

>>> def default_json(t): ... return f'{t}' ... >>> json.dumps({'value': u}, default=default_json) '{"value": "42342.23"}' >>> json.dumps({'value': v}, default=default_json) '{"value": "2020-01-01 00:00:00"}'

Great! All the problems have been fixed! Yay! Right? ...right? Not exactly. This hack is an easy way to get past the initial error. Now we need to actually solve the problem. Luckily, Python has a very robust framework to Encode and Decode JSON: https://docs.python.org/3/library/json.html#encoders-and-decoders.

Good luck and happy Decoding!

-Sethers