I am having what appears to be a common problem but so far I can't see a solution that applies to me. I think I'm just missing something small but I've broken down to ask for help. I am trying to get json output using flask and pymongo.
here is the object in the console using print(results):
[{'_id': ObjectId('598b5de38161a821188f1a7c'), 'first name': 'first name', 'last Name': 'last name'}]
when I try to return on that I get the error: TypeError: Object of type 'ObjectId' is not JSON serializable
class Contacts(Resource):
def get(self):
results =[]
connect = MongoClient("<REMOVED>")
db = connect['<REMOVED>']
collection = db['contact']
contacts = collection.find()
if collection:
number_of_contacts = collection.count()
for document in contacts:
results.append(document)
print(results)
return {'results': results, 'count': number_of_contacts}
I've tried the bson.json_util suggestions. It did clear the serializable error by double encoding my json object. Seems like that isn't a good solution for what I'm doing.
Looks like an easy solution is to just convert the _id to a string which works for what we are trying to do.
for document in contacts:
document['_id'] = str(document['_id'])
results.append(document)
Found solution reading Getting 'TypeError: ObjectId('') is not JSON serializable' when using Flask 0.10.1
I think this will be helpful for you.
from flask import Response
...
...
list_of_books = mongo_db.db[BOOK_COLLECTION].find()
list_of_books = [each_book for each_book in list_of_books]
return Response(json.dumps(list_of_books,default=str),mimetype="application/json")
from bson import json_util
items = mongo.db.shop_items.find_one({"item_name": "abc"})
return make_response(json_util.dumps({"items": items}), HTTPStatus.OK)
---this solved my error.
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