Answer a question

I'm setting up MongoDB for my Python app, and have this code:

@app.route('/user/<firstName>', methods=['GET'])
def getUser(firstName):
    print(firstName)
    return jsonify({'users': Users.find({'first_name': firstName})[0]})

which throws this error: TypeError: Object of type ObjectId is not JSON serializable due to the _id field being '_id': ObjectId('5e8676dc0d16f3567167d889').

How do I get around this?

Answers

Found this code somewhere, and it's working now. *Please tag if anyone knows where this came from.

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

Logo

MongoDB社区为您提供最前沿的新闻资讯和知识内容

更多推荐