Tag Archives: Flask-RESTful

[Solved] MongoDB Error: TypeError: Object of type ObjectId is not JSON serializable

Scene description

After the MongoDB database is used to insert data, an error is reported when the flash restful interface is used to return data:

TypeError: Object of type ObjectId is not JSON serializable

Cause analysis

The reason for this problem is that when data is written to MongoDB, even if you do not specify a _id field, a field will be automatically generated for each piece of data _id, for example:

{
    "_id" : ObjectId("6180af3ef261f0827ea248d6"),
    "省份名称" : "澳门",
    "省份链接" : "https://www.gongkaoleida.com/area/3509",
    "省份代号" : "3509"
}

This field is of ObjectId type and cannot be returned using JSON serialization, so an error will be reported

Solution:

Since _id field cannot be converted and has no effect on our actual data. Then pop it up after inserting the data. An example is as follows:

self.db.filter_result.insert_one(item)
item.pop('_id')