How to overcome “datetime.datetime not JSON serializable”?

后端 未结 30 2731
梦谈多话
梦谈多话 2020-11-22 03:31

I have a basic dict as follows:

sample = {}
sample[\'title\'] = \"String\"
sample[\'somedate\'] = somedatetimehere
         


        
30条回答
  •  忘了有多久
    2020-11-22 04:03

    Building on other answers, a simple solution based on a specific serializer that just converts datetime.datetime and datetime.date objects to strings.

    from datetime import date, datetime
    
    def json_serial(obj):
        """JSON serializer for objects not serializable by default json code"""
    
        if isinstance(obj, (datetime, date)):
            return obj.isoformat()
        raise TypeError ("Type %s not serializable" % type(obj))
    

    As seen, the code just checks to find out if object is of class datetime.datetime or datetime.date, and then uses .isoformat() to produce a serialized version of it, according to ISO 8601 format, YYYY-MM-DDTHH:MM:SS (which is easily decoded by JavaScript). If more complex serialized representations are sought, other code could be used instead of str() (see other answers to this question for examples). The code ends by raising an exception, to deal with the case it is called with a non-serializable type.

    This json_serial function can be used as follows:

    from datetime import datetime
    from json import dumps
    
    print dumps(datetime.now(), default=json_serial)
    

    The details about how the default parameter to json.dumps works can be found in Section Basic Usage of the json module documentation.

提交回复
热议问题