1. 程式人生 > >pymongo中處理ObjectId & datetime型別無法轉為json

pymongo中處理ObjectId & datetime型別無法轉為json

資料庫儲存格式:
{’_id’: ObjectId(‘5bd8f7379e8cc50aa4ed7eab’), ‘time’:datetime.datetime(2018, 10, 31, 8, 58, 7, 889000)}
查詢時出現錯誤:
TypeError: the JSON object must be str, bytes or bytearray, not ‘dict’

pymongo中處理ObjectId & datetime型別無法轉為json

from bson import ObjectId
import datetime

class JSONEncoder
(json.JSONEncoder): """處理ObjectId & datetime型別無法轉為json""" def default(self, o): if isinstance(o, ObjectId): return str(o) if isinstance(o, datetime.datetime): return datetime.datetime.strftime(o, '%Y-%m-%d %H:%M:%S') return json.JSONEncoder.
default(self, o) # 例項查詢資料 cursor = db.collection.find({}) for ret in cursor: ret = JSONEncoder().encode(ret) print(' 查詢結果(json格式)': ret) >>>查詢結果(json格式){"_id": "5bd8f7379e8cc50aa4ed7eab", "time": "2018-10-31 08:58:07"}