Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object of type 'ObjectID' is not JSON serializable

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.

like image 913
Nicholas Elliott Avatar asked Aug 10 '17 13:08

Nicholas Elliott


3 Answers

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

like image 155
Nicholas Elliott Avatar answered Nov 15 '22 07:11

Nicholas Elliott


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")
like image 37
Nandakumar M Avatar answered Nov 15 '22 09:11

Nandakumar M


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.

like image 21
Lalit Garghate Avatar answered Nov 15 '22 09:11

Lalit Garghate