解决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)

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM