Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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:

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?

like image 855
Tarun Dugar Avatar asked May 19 '15 18:05

Tarun Dugar


2 Answers

Use dumps from 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"}}]'
like image 167
Bernie Hackett Avatar answered Oct 14 '22 01:10

Bernie Hackett


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
like image 45
Shashwat Gupta Avatar answered Oct 13 '22 23:10

Shashwat Gupta