我正在为我的 Python 应用程序设置 MongoDB,并有以下代码:
@app.route('/user/<firstName>', methods=['GET'])
def getUser(firstName):
print(firstName)
return jsonify({'users': Users.find({'first_name': firstName})[0]})
抛出此错误:TypeError:ObjectId 类型的对象不可 JSON 序列化
由于 _id
字段为“_id”:ObjectId('5e8676dc0d16f3567167d889')。
我该如何解决这个问题?
最佳答案
在某处找到了这段代码,它现在可以工作了。 *如果有人知道这来自哪里,请标记。
class JSONEncoder(json.JSONEncoder):
''' extend json-encoder class'''
def default(self, o):
if isinstance(o, ObjectId):
return str(o)
if isinstance(o, datetime.datetime):
return str(o)
return json.JSONEncoder.default(self, o)
# use the modified encoder class to handle ObjectId & datetime object while jsonifying the response.
app.json_encoder = JSONEncoder
关于python - "ObjectId is not JSON serializable?"时如何正确jsonify Mongo DB文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61020574/