解决TypeError: Object of type 'ObjectId' is not JSON serializable

 1 import json
 2 from bson import ObjectId
 3 class JSONEncoder(json.JSONEncoder):
 4     '''
 5     解决TypeError: Object of type 'ObjectId' is not JSON serializable
 6     '''
 7     #ensure_ascii解决中文乱码问题,根据自己情况天假
 8     def __init__(self, ensure_ascii=False):
 9         super().__init__(ensure_ascii=False)
10     def default(self, o):
11         if isinstance(o, ObjectId):
12             return str(o)
13         return json.JSONEncoder.default(self, o)
14 
15
#JSONEncoder().encode(res)功能与json.dumps(res,ensure_ascii=False)相同
  1. 使用方法
JSONEncoder().encode(res)

 

posted on 2020-11-22 23:11  川洋  阅读(2231)  评论(0编辑  收藏  举报