Search code examples
pythonjsondatetimecherrypy

Cannot serialize datetime as JSON from Cherrypy


I'm attempting to send a list of records in response to an Ajax query. This works well unless the results include a datetime field when my process fails with the error datetime.date(2011, 11, 1) is not JSON serializable.

I attempted to combine the answer I found to a very similar question here with instructions in the CherryPy documentation to use a custom json_out encoder, but it's not clear to me what signature that function must have. The function I wrote is:

 def json_encoder(thing):

      if hasattr(thing, 'isoformat'):
           return thing.isoformat()
      else:
           return str(thing)

and now any use of json_out (even with no datetime in the output) gives me the error TypeError: json_encoder() takes exactly 1 argument (0 given). But if the encoder doesn't take an argument, how does it receive the object to encode?

(Also, I assume my use of str(thing) as the default method of encoding is wrong and that this should be done with a call to whatever the default handler for json encoding is, but I'm not sure how to call that method).


Solution

  • I do the next in a similar case:

    class DecimalEncoder(json.JSONEncoder):
        def default(self, obj):
            if isinstance(obj, Decimal):
                return float(obj)
            return json.JSONEncoder.default(self, obj)
    

    and at the call:

    json.dumps(my_variable, cls=DecimalEncoder)
    

    So in your case it should be like:

    class DateEncoder(json.JSONEncoder):
        def default(self, obj):
            if hasattr(obj, 'isoformat'):
                return obj.isoformat()
            else:
                return str(obj)
            return json.JSONEncoder.default(self, obj)
    
    
    json.dumps(my_variable, cls=DateEncoder)