TypeError: Collection(Database(MongoClient("localhost", 27017), u'demo_database'), u'entries) is not JSON serializable
Question: Good afternoon.

I'm trying to combine Python, MongoDB (via pymongo) and Flask to create
client-server application. I want to use one of methods to return all the
entire collection, like here:

    
    
    @app.route('/entries', methods = ['GET'])
    def get_entries():
        client = MongoClient(db_host, db_port)
        db_demo = client['demo_database']
        entries = db_demo.entries
        return JSONEncoder().encode(entries)
    

I also have an **Encoder** class, as advised
[here](http://stackoverflow.com/questions/16586180/typeerror-objectid-is-not-
json-serializable):

    
    
    class JSONEncoder(json.JSONEncoder):
        def default(self, o):
            if isinstance(o, ObjectId):
                return str(o)
            return json.JSONEncoder.default(self, o)
    

Data collection is very simple - actually, only one item with few fields. What
am I doing wrong? Perhaps I should develop more sophisticated encoder class?


Answer: Use
[bson.json_util.dumps](http://api.mongodb.org/python/current/api/bson/json_util.html#bson.json_util.dumps),
which already supports all the MongoDB extended JSON types:

    
    
    >>> from bson.json_util import dumps
    >>> c.test.test.insert_many([{} for _ in range(3)])
    <pymongo.results.InsertManyResult object at 0x7f6ed3189550>
    >>> dumps(c.test.test.find())
    '[{"_id": {"$oid": "554faa99fa5bd8782e1698cf"}}, {"_id": {"$oid": "554faa99fa5bd8782e1698d0"}}, {"_id": {"$oid": "554faa99fa5bd8782e1698d1"}}]'
    

