{"id":256,"hash":"1528f1a491db3d073fe9ba96341e99930fd0bb99cac0bf52bfff04ebbc79f82e","pattern":"TypeError: ObjectId(&#39;&#39;) is not JSON serializable","full_message":"My response back from MongoDB after querying an aggregated function on document using Python, It returns valid response and i can print it but can not return it.\n\nError: \n\nTypeError: ObjectId('51948e86c25f4b1d1c0d303c') is not JSON serializable\n\nPrint:\n\n{'result': [{'_id': ObjectId('51948e86c25f4b1d1c0d303c'), 'api_calls_with_key': 4, 'api_calls_per_day': 0.375, 'api_calls_total': 6, 'api_calls_without_key': 2}], 'ok': 1.0}\n\nBut When i try to return:\n\nTypeError: ObjectId('51948e86c25f4b1d1c0d303c') is not JSON serializable\n\nIt is RESTfull call:\n\n@appv1.route('/v1/analytics')\ndef get_api_analytics():\n    # get handle to collections in MongoDB\n    statistics = sldb.statistics\n\n    objectid = ObjectId(\"51948e86c25f4b1d1c0d303c\")\n\n    analytics = statistics.aggregate([\n    {'$match': {'owner': objectid}},\n    {'$project': {'owner': \"$owner\",\n    'api_calls_with_key': {'$cond': [{'$eq': [\"$apikey\", None]}, 0, 1]},\n    'api_calls_without_key': {'$cond': [{'$ne': [\"$apikey\", None]}, 0, 1]}\n    }},\n    {'$group': {'_id': \"$owner\",\n    'api_calls_with_key': {'$sum': \"$api_calls_with_key\"},\n    'api_calls_without_key': {'$sum': \"$api_calls_without_key\"}\n    }},\n    {'$project': {'api_calls_with_key': \"$api_calls_with_key\",\n    'api_calls_without_key': \"$api_calls_without_key\",\n    'api_calls_total': {'$add': [\"$api_calls_with_key\", \"$api_calls_without_key\"]},\n    'api_calls_per_day': {'$divide': [{'$add': [\"$api_calls_with_key\", \"$api_calls_without_key\"]}, {'$dayOfMonth': datetime.now()}]},\n    }}\n    ])\n\n    print(analytics)\n\n    return analytics\n\ndb is well connected and collection is there too and I got back valid expected result but when i try to return it gives me Json error. Any idea how to convert the response back into JSON. Thanks","ecosystem":"pypi","package_name":"json","package_version":null,"solution":"You should define you own JSONEncoder and using it:\n\nimport json\nfrom bson import ObjectId\n\nclass JSONEncoder(json.JSONEncoder):\n    def default(self, o):\n        if isinstance(o, ObjectId):\n            return str(o)\n        return json.JSONEncoder.default(self, o)\n\nJSONEncoder().encode(analytics)\n\nIt's also possible to use it in the following way. \n\njson.encode(analytics, cls=JSONEncoder)","confidence":0.95,"source":"stackoverflow","source_url":"https://stackoverflow.com/questions/16586180/typeerror-objectid-is-not-json-serializable","votes":185,"created_at":"2026-04-19T04:41:39.772852+00:00","updated_at":"2026-04-19T04:51:51.426224+00:00"}