Pymongo / bson:python.cursor进行转换。将光标对象指向serializable/JSON对象

时间:2023-01-11 08:40:48

New to MongoDb and Python (webapp2). So, I was fetching some data from a mongodb database. But I was unable to use json.dumps on the returned data. Here's my code:

MongoDb和Python (webapp2)的新特性。因此,我正在从mongodb数据库中获取一些数据。但是我不能使用json。转储返回的数据。这是我的代码:

exchangedata = db.Stock_Master.find({"Country": "PHILIPPINES"}, {"_id" : 0})        
self.response.write(json.dumps(exchangedata)) 

This throws an error:

这将抛出一个错误:

TypeError: pymongo.cursor.Cursor object at 0x7fcd51230290 is not JSON serializable

The type of exchangedata is pymongo.cursor.Cursor. How can I convert it into a json object?

交换数据的类型是pymongo.cursor.Cursor。如何将其转换为json对象?

1 个解决方案

#1


20  

Use dumps from bson.json_util:

使用转储bson.json_util:

>>> c = pymongo.MongoClient()
>>> c.test.test.count()
5
>>> from bson.json_util import dumps
>>> dumps(c.test.test.find())
'[{"_id": {"$oid": "555cb3a7fa5bd85b81d5a624"}}, {"_id": {"$oid": "555cb3a7fa5bd85b81d5a625"}}, {"_id": {"$oid": "555cb3a7fa5bd85b81d5a626"}}, {"_id": {"$oid": "555cb3a7fa5bd85b81d5a627"}}, {"_id": {"$oid": "555cb3a7fa5bd85b81d5a628"}}]'

#1


20  

Use dumps from bson.json_util:

使用转储bson.json_util:

>>> c = pymongo.MongoClient()
>>> c.test.test.count()
5
>>> from bson.json_util import dumps
>>> dumps(c.test.test.find())
'[{"_id": {"$oid": "555cb3a7fa5bd85b81d5a624"}}, {"_id": {"$oid": "555cb3a7fa5bd85b81d5a625"}}, {"_id": {"$oid": "555cb3a7fa5bd85b81d5a626"}}, {"_id": {"$oid": "555cb3a7fa5bd85b81d5a627"}}, {"_id": {"$oid": "555cb3a7fa5bd85b81d5a628"}}]'