close

[Solved] TypeError: ObjectId(”) is not JSON serializable

Hello Guys, How are you all? Hope You all Are Fine. Today I get the following error TypeError: ObjectId(”) is not JSON serializable in python. So Here I am Explain to you all the possible solutions here.

Without wasting your time, Let’s start This Article to Solve This Error.

How TypeError: ObjectId(”) is not JSON serializable Error Occurs?

Today I get the following error TypeError: ObjectId(”) is not JSON serializable in python.

How To Solve TypeError: ObjectId(”) is not JSON serializable Error ?

  1. How To Solve TypeError: ObjectId('') is not JSON serializable Error ?

    To Solve TypeError: ObjectId('') is not JSON serializable Error Pymongo provides json_util – you can use that one instead to handle BSON types

  2. TypeError: ObjectId('') is not JSON serializable

    To Solve TypeError: ObjectId('') is not JSON serializable Error Pymongo provides json_util – you can use that one instead to handle BSON types

Solution 1

Pymongo provides json_util – you can use that one instead to handle BSON types

def parse_json(data):
    return json.loads(json_util.dumps(data))

Solution 2

You should define you own JSONEncoder and using it:

import json
from bson import ObjectId

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

JSONEncoder().encode(analytics)

It’s also possible to use it in the following way.

json.encode(analytics, cls=JSONEncoder)

Summery

It’s all About this issue. Hope all solution helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which solution worked for you? Thank You.

Also, Read