mongodb 序列化问题

在使用MongoDB时总是会和数据的ID打交道,MongoDB的ID使用的是ObjectId对象类型。ObjectId无法通过json序列化,需要转换。

错误:

TypeError: ObjectId('5cb58e2b8b403d177092b667') is not JSON serializable
1
解决方法,将ObjectId对象转成字符串,使用中直接使用'5cb58e2b8b403d177092b667'即可。

from bson import ObjectId
import json

class JSONEncoder(json.JSONEncoder):
def default(self, o):
if isinstance(o, ObjectId):
return str(o)
return json.JSONEncoder.default(self, o)

res = json.dumps(DBResultMessage, cls=JSONEncoder)

该方法是本人觉得比较简单好用的方案之一。同理,该方法也可以用于其他json不支持的格式转换,比如datetime类型,只需要将函数中类型变成datetime,返回值转换成希望的字符格式即可。

原文地址:https://www.cnblogs.com/hanzeng1993/p/11413401.html