Object of type 'ObjectID' is not JSON serializable

Nicholas Elliott picture Nicholas Elliott · Aug 10, 2017 · Viewed 8.9k times · Source

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.

Answer

Nicholas Elliott picture Nicholas Elliott · Aug 10, 2017

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