Search code examples
pythonflaskpymongoflask-mongoengine

TypeError TypeError: Object of type ObjectId is not JSON serializable


I am trying to write a Python Flask program to read my MongoDB Database and output the table in Json format. My flask seems to run, as I am able to get into the default endpoint, but my second endpoint gives me the below error. Any feedback would be appreciated.

TypeError: Object of type ObjectId is not JSON serializable

This is my Code.

My Database name is "movies_db" and the Collection name is "movie_info".

from flask import Flask, jsonify
from pymongo import MongoClient

app = Flask(__name__)

# Replace with MongoDB connection details
mongo_client = MongoClient('mongodb://localhost:27017/')
db = mongo_client['movies_db']

@app.route('/')
def index():
    return 'Welcome to my Project!'


import json

@app.route('/export-json', methods=['GET', 'POST'])
def export_json():
    collection_name = 'movie_info'  

    data = list(db[collection_name].find({}))

    # Convert data to JSON using Flask's jsonify
    json_data = jsonify(data).get_json()

    # Write JSON data to a file
    with open('data.json', 'w') as json_file:
        json.dump(json_data, json_file, indent=4)

    return jsonify({'message': 'Data exported to data.json'})

if __name__ == '__main__':
    app.run()`

I've tried using the solution in this link, but still no luck.

TypeError: ObjectId('') is not JSON serializable


Solution

  • If you're not bothered about the _id fields you can exclude it by changing your find() to exlcude the field.

    data = list(db[collection_name].find({}, {'_id': 0})
    

    This won't help if you have other ObjectIds in the record though.