解決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