Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return MongoEngine Documents as JSON

Not too sure if this is really simple or not, but I can't really find anything on the topic. But, either using the regular MongoEngine library, or even Flask-MongoEngine for my Flask based website, would it be possible to return a MongoEngine document as straight JSON?

Thanks!

like image 707
Chiggins Avatar asked Dec 03 '12 16:12

Chiggins


4 Answers

Update: thanks to Lo-Tan for to_mongo() method usage suggestion.

Eventually I came up with the following solution:

from json import JSONEncoder

from mongoengine.base import BaseDocument


class MongoEncoder(JSONEncoder):
    def default(self, o):
        if isinstance(o, BaseDocument):
            data = o.to_mongo()
            # might not be present if EmbeddedDocument
            o_id = data.pop('_id', None)
            if o_id:
                data['id'] = str(o_id['$oid'])
            data.pop('_cls', None)
            return data
        else:
            return JSONEncoder.default(self, o)


# consider `obj` to be MongoEngine object
json_data = json.dumps(obj, cls=MongoEncoder)

It uses to_json() method, added as the response to the aforementioned issue.

like image 173
Serge Mosin Avatar answered Oct 22 '22 22:10

Serge Mosin


Ross's and Jellyflower's workarounds don't work when field projection or ordering is used.

More general workaround:

from bson import json_util
json = json_util.dumps(query._cursor)
like image 23
henadzit Avatar answered Oct 22 '22 21:10

henadzit


In 0.8 there are helpers see https://github.com/MongoEngine/mongoengine/issues/1

in the meantime you have to use pymongo's json_utils directly:

from bson import json_util
json_util.dumps(MyDoc._collection_obj.find(MyDoc.objects()._query))
like image 45
Ross Avatar answered Oct 22 '22 22:10

Ross


The correct workaround should probably be:

from bson import json_util
objects = MyDoc.objects()
json_util.dumps(objects._collection_obj.find(objects._query))
like image 35
Dr. Alpha Avatar answered Oct 22 '22 23:10

Dr. Alpha