TypeError: ObjectId('') is not JSON serializable
You should define you own JSONEncoder
and using it:
import json
from bson import ObjectId
class JSONEncoder(json.JSONEncoder):
def default(self, o):
if isinstance(o, ObjectId):
return str(o)
return json.JSONEncoder.default(self, o)
JSONEncoder().encode(analytics)
It's also possible to use it in the following way.
json.encode(analytics, cls=JSONEncoder)
Getting 'TypeError: ObjectId('') is not JSON serializable' when using Flask 0.10.1
EDIT: Even easier fix. You don't even need to do any JSON encoding/decoding.
Just save the session['_id'] as a string:
user = db.minitwit.user.find_one({'username': request.form['username']})
session['_id'] = str(user['_id'])
And then everywhere you want to do something with the session['_id'] you have to wrap it with ObjectId() so it's passed as a ObjectId object to MongoDB.
if '_id' in session:
g.user = db.minitwit.user.find_one({'_id': session['_id']})
to:
if '_id' in session:
g.user = db.minitwit.user.find_one({'_id': ObjectId(session['_id'])})
You can see the full diff for the fix on my github repo.
If anyone cares to know why the 'TypeError: ObjectId('') is not JSON serializable' "issue" appeared in Flask 0.10.1, it's because they changed the way sessions are stored. They are now stored as JSON so since the '_id' object in MongoDB isn't standard JSON, it failed to serialize the session token, thus giving the TypeError. Read about the change here: http://flask.pocoo.org/docs/upgrading/#upgrading-to-010
TypeError: Object of type 'ObjectId' is not JSON serializable using Flask and MongoDB
When inserting a document into MongoDB, if you don't specify an _id
field, the pymongo drivers will add an _id
field of type ObjectId
to the document, before inserting into the database.
See https://pymongo.readthedocs.io/en/stable/faq.html#writes-and-ids
Flask is then trying to JSON serialise the field which it doesn't know how to do; hence the error.
A simple fix could be to just pop
the _id
before returning it; e.g.
# insert into database 's41', collection 'links'
db_s41.links.insert_one(new_link_doc)
new_link_doc.pop('_id')
return new_link_doc
TypeError Object id is not JSON serializable
The error is because you are trying to save a model instance in the session, and the session middleware cannot serialize it to JSON.
request.session['content'] = model1object
It may be enough to store the id of the object instead of the object itself.
request.session['content_id'] = model1object.id
...
# retrieve from db later
model1object = Model1.objects.get(id=request.session['content_id'])
If you need to store more information in the session than the id, then you'll have to convert it to a format that is JSON serializable. For a simple model, it might be easiest to create a Python dict.
request.session['content'] = {
'id': model1object.id,
'name': model1object.name,
...
}
For more complicated models, you could look at the docs on serializing Django objects.
Related Topics
Style Active Navigation Element with a Flask/Jinja2 MACro
Color Coding Cells in a Table Based on the Cell Value Using Jinja Templates
How to Pull Out CSS Attributes from Inline Styles with Beautifulsoup
Multiple Level Template Inheritance in Jinja2
Control the Size Textarea Widget Look in Django Admin
Python How to Parse CSS File as Key Value
How to Highlight Searched Queries in Result Page of Django Template
Using Beautiful Soup to Convert CSS Attributes to Individual HTML Attributes
Best Way to Set Entry Background Color in Python Gtk3 and Set Back to Default
I Can't Import Python Modules in Xcode 11 Using Pythonkit
Generate Correlated Data in Python (3.3)
In Python Interpreter, Return Without " ' "
Python Sockets Error Typeerror: a Bytes-Like Object Is Required, Not 'Str' with Send Function
Python MySQL Connector Database Query with %S Fails