datetime.date(2014, 4, 25) is not JSON serializable

简介: # 背景 接口期望返回json格式数据,但数据存储在mysql中,先将mysql的数据转为dict,然后将dict转为json格式,然后就报这个错误了的,原因就是时间格式转换问题   # 解决方法 1.

# 背景

接口期望返回json格式数据,但数据存储在mysql中,先将mysql的数据转为dict,然后将dict转为json格式,然后就报这个错误了的,原因就是时间格式转换问题

 

# 解决方法

1. 创建这么一个方法

def date_handler(obj):
    if hasattr(obj, 'isoformat'):
        return obj.isoformat()
    else:
        raise TypeError

2. 然后这样转换:

json.dumps(people.as_dict(), default=date_handler)
people.as_dict()是将mysql数据转为dict格式

虽千万人,吾往矣!
目录
相关文章
|
JSON 数据格式
成功解决TypeError: Object of type 'ndarray' is not JSON serializable
成功解决TypeError: Object of type 'ndarray' is not JSON serializable
|
2月前
|
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类型的数据。
63 1
|
3月前
|
JSON 前端开发 数据格式
【Python】已解决:TypeError: Object of type JpegImageFile is not JSON serializable
【Python】已解决:TypeError: Object of type JpegImageFile is not JSON serializable
58 0
|
JSON 数据格式
TypeError: Object of type ‘float32‘ is not JSON serializable
TypeError: Object of type ‘float32‘ is not JSON serializable
191 0
|
JSON 数据格式 Python
TypeError: Object of type 'datetime' is not JSON serializable
TypeError: Object of type 'datetime' is not JSON serializable
172 0
|
JSON 数据格式 Python
pymongo:Object of type ObjectId is not JSON serializable
1.问题原因 是由于ObjectId无法在服务端生成json数据 请在文件头引入这两个python包
278 0
|
JSON 数据格式
TypeError: Object of type 'datetime' is not JSON serializable
TypeError: Object of type 'datetime' is not JSON serializable
126 0
|
10天前
|
XML 存储 JSON
Twaver-HTML5基础学习(19)数据容器(2)_数据序列化_XML、Json
本文介绍了Twaver HTML5中的数据序列化,包括XML和JSON格式的序列化与反序列化方法。文章通过示例代码展示了如何将DataBox中的数据序列化为XML和JSON字符串,以及如何从这些字符串中反序列化数据,重建DataBox中的对象。此外,还提到了用户自定义属性的序列化注册方法。
27 1
|
7天前
|
存储 JSON Go
在Gin框架中优雅地处理HTTP请求体中的JSON数据
在Gin框架中优雅地处理HTTP请求体中的JSON数据
|
11天前
|
JSON JavaScript 数据格式
vue写入json数据到文本中+vue引入cdn的用法
vue写入json数据到文本中+vue引入cdn的用法
下一篇
无影云桌面