Skip to content Skip to sidebar Skip to footer

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 = d

Solution 1:

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

Solution 2:

Simple Solution

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

@app.route("/")defhome_page():

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

Solution 3:

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.

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)

Post a Comment for "Pymongo/bson: Convert Python.cursor.cursor Object To Serializable/json Object"