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"}
 

你可能感兴趣的:(数据库操作)