JSON Encoding mongoDB Documents in Python
One thing that kept puzzling me about pymongo was that I couldn’t a
serialize a document as JSON. Aren’t these things just fancy JSON
objects on the backend? Well, they are – but ObjectId is part of
mongoDB extension of JavaScript so there is no JSON-equivalent. And
since Python only knows about the standard JSON spec, it won’t know
what to do with ObjectId instances.
When attempting to encode a Python dictionary which has an ObjectId
as one of its values, I get a TypeError saying ObjectId “is not
JSON serializable”.
My solution is to extend the JSONEncoder included in Python’s json
module (in 2.6 or later)
It adds a special case to handle encoding an ObjectId into a literal
“ObjectId” in the encoded JSON.
Custom JSON encoders can be used when issuing json.dump or json.dumps
by specifying cls
json.dump(obj, cls=MongoEncoder)
E.g.,
>>> import json >>> from pymongo.objectid import ObjectId >>> from mongoencoder import MongoEncoder >>> x = {'a':1,'b':"foo",'c':ObjectId()} >>> print x {'a': 1, 'c': ObjectId('4c4f4f5e2554c813e4000001'), 'b': 'foo'} >>> print json.dumps(x) Traceback (most recent call last): [...] TypeError: ObjectId('4c4f4f5e2554c813e4000001') is not JSON serializable >>> print json.dumps(x, cls=MongoEncoder) '{"a": 1, "c": ObjectId("4c4f4f5e2554c813e4000001"), "b": "foo"}'
Viola! Enjoy
