TypeError: Object of type 'datetime' is not JSON serializable

简介: TypeError: Object of type 'datetime' is not JSON serializable

json序列化时间对象的时候报错:

    TypeError: Object of type 'datetime' is not JSON serializable

解决办法


重写json序列化类

# -*- coding: utf-8 -*-


import json

import datetime


class DateEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, datetime.datetime):
return obj.strftime('%Y-%m-%d %H:%M:%S')

elif isinstance(obj, datetime.date):
return obj.strftime("%Y-%m-%d")

else:
return json.JSONEncoder.default(self, obj)


if name == '__main__':
data = {"name": "Tom", "birthday": datetime.datetime.now()}
print(json.dumps(data, cls=DateEncoder))
# {"name": "Tom", "birthday": "2019-06-06 17:24:19"}

参考:

python datetime.datetime is not JSON serializable 报错问题解决

            </div>
目录
相关文章
|
JSON 数据格式
成功解决TypeError: Object of type 'ndarray' is not JSON serializable
成功解决TypeError: Object of type 'ndarray' is not JSON serializable
|
JSON 数据格式
解决报错TypeError: Converting circular structure to JSON --> starting at object with constructor
解决报错TypeError: Converting circular structure to JSON --> starting at object with constructor
|
存储 JSON JavaScript
【Python】已完美解决:TypeError: the JSON object must be str, bytes or bytearray, not dict
【Python】已完美解决:TypeError: the JSON object must be str, bytes or bytearray, not dict
838 1
|
JSON 前端开发 数据格式
【Python】已解决:TypeError: Object of type JpegImageFile is not JSON serializable
【Python】已解决:TypeError: Object of type JpegImageFile is not JSON serializable
438 0
|
JSON 数据格式 Python
TypeError the JSON object must be str, bytes or bytearray, not ‘list‘
TypeError the JSON object must be str, bytes or bytearray, not ‘list‘
441 1
|
JSON 数据格式 Python
Python报错:TypeError: the JSON object must be str, bytes or bytearray, not ‘dict‘
Python报错:TypeError: the JSON object must be str, bytes or bytearray, not ‘dict‘
1959 0
|
JSON 数据格式
TypeError: Object of type ‘float32‘ is not JSON serializable
TypeError: Object of type ‘float32‘ is not JSON serializable
384 0
|
JSON 数据格式 Python
TypeError: Object of type 'datetime' is not JSON serializable
TypeError: Object of type 'datetime' is not JSON serializable
245 0
|
JSON 数据格式 Python
TypeError: Object of type 'datetime' is not JSON serializable
TypeError: Object of type 'datetime' is not JSON serializable
164 0
|
JSON 数据格式
TypeError: Object of type 'datetime' is not JSON serializable
TypeError: Object of type 'datetime' is not JSON serializable
204 0

热门文章

最新文章