Return MongoEngine Documents as JSON

Chiggins picture Chiggins · Dec 3, 2012 · Viewed 8.6k times · Source

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!

Answer

Ross picture Ross · Dec 3, 2012

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))