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 数据格式 Python
【python】解决json.dump(字典)时报错Object of type ‘float32‘ is not JSON serializable
在使用json.dump时遇到的“Object of type ‘float32’ is not JSON serializable”错误的方法,通过自定义一个JSON编码器类来处理NumPy类型的数据。
793 1
|
SQL JSON 分布式计算
hive get_json_object解析json结果为null咋办?
解决get_json_object解析json结果为null的问题
1202 0
|
JSON 关系型数据库 MySQL
MySQL中GROUP_CONCAT与JSON_OBJECT、GROUP BY的巧妙结合:打造高效JSON数组汇总
MySQL中GROUP_CONCAT与JSON_OBJECT、GROUP BY的巧妙结合:打造高效JSON数组汇总
587 1
|
JSON 前端开发 数据格式
【Python】已解决:TypeError: Object of type JpegImageFile is not JSON serializable
【Python】已解决:TypeError: Object of type JpegImageFile is not JSON serializable
434 0
|
SQL JSON 关系型数据库
MYSQL--JSON_OBJECT 和 JSON_ARRAYAGG
MYSQL--JSON_OBJECT 和 JSON_ARRAYAGG
633 0
|
JSON 数据格式
TypeError: Object of type ‘float32‘ is not JSON serializable
TypeError: Object of type ‘float32‘ is not JSON serializable
383 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
163 0
|
JSON 数据格式 Python
pymongo:Object of type ObjectId is not JSON serializable
1.问题原因 是由于ObjectId无法在服务端生成json数据 请在文件头引入这两个python包
446 0