Learning about json

While working quickly towards a production release I ran across a problem that looked something like this:

>>> import datetime
>>> import json
>>> mydict = {'name':'fred',
...     'inserted': datetime.datetime.now()}
>>> mydict
{'name': 'fred', 'inserted': datetime.datetime(2018, 7, 2, 21, 0, 49,
542337)}
>>> json.dumps(mydict)

Traceback (most recent call last):
  ...
  TypeError: Object of type 'datetime' is not JSON serializable

Whoops, that’s not going to work! Hmm, I wonder how the json package handles complex objects that have to be serialized in some way? Fortunately I found the answer looking at the help for json.dumps:

>>>help(json.dumps)
    ...
    ``default(obj)`` is a function that should return a serializable version
	of obj or raise TypeError. The default simply raises
	TypeError.
	...	

Well let’s see what that would look like. With some trial and error I ended up implementing something like this.

def dtSerializer(obj):
     if isinstance(obj, datetime.datetime):
             return(obj.isoformat())
     else:
             TypeError("Unknown serializer")

Now I can call json.dumps with the default parameter and expect something better than a TypeError exception.

>>> json.dumps(mydict,default=dtSerializer)
'{"name": "fred", "inserted": "2018-07-02T21:00:49.542337"}'

Whew! Tragedy averted. I can continue with the production deployment.