Pymongo/bson:将 python.cursor.Cursor 对象转换为可序列化/JSON 对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30333299/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 08:16:43  来源:igfitidea点击:

Pymongo/bson: Convert python.cursor.Cursor object to serializable/JSON object

pythonjsonmongodbpymongowebapp2

提问by Tarun Dugar

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

MongoDb 和 Python ( webapp2) 的新手。所以,我从mongodb数据库中获取了一些数据。但是我无法json.dumps在返回的数据上使用。这是我的代码:

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 exchangedatais pymongo.cursor.Cursor. How can I convert it into a json object?

的类型exchangedatapymongo.cursor.Cursor。如何将其转换为 json 对象?

采纳答案by Bernie Hackett

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

回答by Shashwat Gupta

Simple Solution

简单的解决方案

 // Use dumps from bson.json_util:
from bson.json_util import dumps

@app.route("/")
def home_page():

    booking = dumps(mongo.db.bookings.find())
    print booking
    return  booking

回答by Shirantha Madusanka

Yes, of course you can use the dumps() in bson.json_util package. But, the dumps() will give you quoted results. To get clear json result you can use the following code.

是的,当然你可以使用 bson.json_util 包中的 dumps() 。但是, dumps() 会给你引用的结果。要获得清晰的 json 结果,您可以使用以下代码。

clean_json = re.compile('ISODate\(("[^"]+")\)').sub('\1', 
        dumps(my_db._my_collection.find(query), 
                 json_options=CANONICAL_JSON_OPTIONS))
json_obj = json.loads(clean_json)

Credits goes to here.

积分到这里