for p in db.collection.find({"test_set":"abc"}): posts.append(p) thejson = json.dumps({'results':posts}) return HttpResponse(thejson, mimetype="application/javascript")
In my Django/Python code, I can't return a JSON from a mongo query because of "ObjectID". The error says that "ObjectID" is not serializable.
What do I have to do? A hacky way would be to loop through:
for p in posts: p['_id'] = ""
Once connected to a MongoDB database, open the Export Wizard by clicking on Export in the Global Toolbar. Alternatively, you can right-click on any server, database, or collection in the Connection Tree and choose Export (Collections, Buckets, Views).
Anything you can represent in JSON can be natively stored in MongoDB, and retrieved just as easily in JSON. The following are some example documents (in JavaScript / Python style syntax) and their corresponding BSON representations.
The json module won't work due to things like the ObjectID.
Luckily PyMongo provides json_util which ...
... allow[s] for specialized encoding and decoding of BSON documents into Mongo Extended JSON's Strict mode. This lets you encode / decode BSON documents to JSON even when they use special BSON types.
Here is a simple sample, using pymongo 2.2.1
import os import sys import json import pymongo from bson import BSON from bson import json_util if __name__ == '__main__': try: connection = pymongo.Connection('mongodb://localhost:27017') database = connection['mongotest'] except: print('Error: Unable to Connect') connection = None if connection is not None: database["test"].insert({'name': 'foo'}) doc = database["test"].find_one({'name': 'foo'}) return json.dumps(doc, sort_keys=True, indent=4, default=json_util.default)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With