Custom JSONEncoder and JSONDecoder to handle datetime in Python’s json library



Sometimes it really surprises me how something as mundane as JSON encoding and decoding datetime objects in Python is not readily solve-able with a simple google query. I guess this is caused by the sheer amount of code fragments floating around confusing The Kraken. With this blag post, I'd happily like to add to this mess:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import json
import datetime


class CustomEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, (datetime.date, datetime.datetime)):
            return obj.isoformat()


class CustomDecoder(json.JSONDecoder):
    def __init__(self, *args, **kwargs):
        super().__init__(object_hook=self.try_datetime, *args, **kwargs)

    @staticmethod
    def try_datetime(d):
        ret = {}
        for key, value in d.items():
            try:
                ret[key] = datetime.datetime.fromisoformat(value)
            except (ValueError, TypeError):
                ret[key] = value
        return ret


json_str = json.dumps({'foo': datetime.datetime.now()}, cls=CustomEncoder)
d = json.loads(json_str, cls=CustomDecoder)
print(type(d['foo']))
# <class 'datetime.datetime'>
That's it. Have a good one. Bye.

Leave a Reply

Your email address will not be published. Required fields are marked *