0

I know many variants of this question have been asked already, but none are really specific to the problem I'm facing.

I'm using MongoDB with a python backend and RESTful API, and I have such code:

cluster = pymongo.Mongoclient("secret_information")
db = cluster['test']
userCollection = db['users']

@app.route('/api/getUsers', methods=['GET'])
def getUsers(): 
    allUsers_cursor = userCollection.find({})
    allUsers = list(allUsers_cursor)

    #the below line gives me "ObjectId is not JSON serializable error" message: 
    return jsonify(allUsers), 200

My database is very simple and looks something like this:

[{
    title: "personA",
    description: "a person"
},
{
    title: "personB",
    description: "another person"
}]

There must be an easy way to deal with the ObjectId problem - I can't imagine that something as ubiquitous to the database as ObjectId would cause such big problems for all users. Help appreciated!

Ryan T. J.
  • 41
  • 2
  • 1
    Does this answer your question? [TypeError: ObjectId('') is not JSON serializable](https://stackoverflow.com/questions/16586180/typeerror-objectid-is-not-json-serializable) – sushanth Jun 29 '20 at 09:21
  • I did refer to that post too. But now the problem is that the returned result is entirely a string, no longer json, so my front-end can't query the response data for specific fields (like "user"). This is to say that I get a response like: `'[{"_id" : "53v123edsadd882s", "title" : "personA", "description" : "a person"}, { ... }]'` and this entire thing is a string – Ryan T. J. Jun 29 '20 at 09:36
  • None of these options work? https://api.mongodb.com/python/current/api/bson/json_util.html. – Tom Slabbaert Jun 29 '20 at 09:42
  • @TomSlabbaert Thanks, I tried deserialization, and it worked! Here's the line of code I'm now using: `return jsonify(json_util.loads(JSONEncoder().encode(allUsers))), 200` Although it works, would you say that this is the right way to be using loads? It feels very unclean, as if there's some sort of redundancy where I first convert allUsers to a string, and then back to a JSON object. – Ryan T. J. Jun 29 '20 at 09:54
  • Turns out, yeah it was redundant. I simplified my code to: `return JSONEncoder().encode(allUsers), 200 ` All's good now. Thank you :) – Ryan T. J. Jun 29 '20 at 09:56

0 Answers0