2

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?

P_equals_NP_2021
  • 627
  • 1
  • 9
  • 27
  • did you see [JSON serializing Mongodb](https://stackoverflow.com/questions/19674311/json-serializing-mongodb) – Joe Apr 04 '20 at 03:46
  • Does this answer your question? [JSON serializing Mongodb](https://stackoverflow.com/questions/19674311/json-serializing-mongodb) – Joe Apr 04 '20 at 03:47
  • @Joe No, they do not. – P_equals_NP_2021 Apr 04 '20 at 04:46
  • If the json_util functions that convert BSON to JSON don't help, what is it you're trying to do? – Joe Apr 04 '20 at 17:52
  • @Joe Trying to jsonify Pymongo objects, but I was able to using a custom JSON encoder. It's due to the ObjectId field not being serializable. – P_equals_NP_2021 Apr 04 '20 at 21:41
  • ObjectId is BSON type, so the json_util functions from the BSON library can serialize it. – Joe Apr 04 '20 at 22:49
  • @Joe That would mean I need to serialize the rest with another JSON library right? – P_equals_NP_2021 Apr 05 '20 at 00:22
  • not really, if you're using a mongodb object, you've already got the BSON library loaded, or python wouldn't know what an ObjectId is. As in, rather than writing a custom function to serialize a BSON type, use the type conversion provided by the BSON library. – Joe Apr 05 '20 at 01:22

1 Answers1

2

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

P_equals_NP_2021
  • 627
  • 1
  • 9
  • 27