JSON serializing Mongodb

后端 未结 5 1471
南笙
南笙 2020-12-05 05:10

I am using the python package pymongo to retrieve data from a mongodb database.

>>> r = collection.find()   # returns an object of class \'Cursor\'
         


        
5条回答
  •  佛祖请我去吃肉
    2020-12-05 05:39

    on my situation, this error is due to mongo DB id object in flask all you have to do is convert id if you need it else you can pop it too I'm sharing my solution which I figured out hope this helps someone

    from flask import jsonify
    
    def get_data(self,data):
         data['_id'] = str(data['_id'])
         return data
    
    app =  Flask(__name__)
    
    @app.route('/')
    def apimethod():
         temp = [self.get_data(i) for i in self.critical.find()]
         return jsonify(temp)
    

    also dumps from pymongo don't help alot

    from bson.json_util import dumps,loads
    

    because it is returning a string instead of dict which was expected in my situation to create API and I have to load again if I did dumps.

提交回复
热议问题