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

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

I have a basic dict as follows:

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


        
30条回答
  •  遥遥无期
    2020-11-22 03:46

    My solution (with less verbosity, I think):

    def default(o):
        if type(o) is datetime.date or type(o) is datetime.datetime:
            return o.isoformat()
    
    def jsondumps(o):
        return json.dumps(o, default=default)
    

    Then use jsondumps instead of json.dumps. It will print:

    >>> jsondumps({'today': datetime.date.today()})
    '{"today": "2013-07-30"}'
    

    I you want, later you can add other special cases to this with a simple twist of the default method. Example:

    def default(o):
        if type(o) is datetime.date or type(o) is datetime.datetime:
            return o.isoformat()
        if type(o) is decimal.Decimal:
            return float(o)
    

提交回复
热议问题