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

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

I have a basic dict as follows:

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


        
30条回答
  •  一向
    一向 (楼主)
    2020-11-22 04:09

    The json.dumps method can accept an optional parameter called default which is expected to be a function. Every time JSON tries to convert a value it does not know how to convert it will call the function we passed to it. The function will receive the object in question, and it is expected to return the JSON representation of the object.

    def myconverter(o):
     if isinstance(o, datetime.datetime):
        return o.__str__()
    
    print(json.dumps(d, default = myconverter)) 
    

提交回复
热议问题