Unable to deserialize PyMongo ObjectId from JSON
Solution 1:
I think your string form actually looks like the python representation...
s = '{"_id": {"$oid": "4edebd262ae5e93b41000000"}}'
u = json.loads(s, object_hook=json_util.object_hook)
print u # Result: {u'_id': ObjectId('4edebd262ae5e93b41000000')}
s = json.dumps(u, default=json_util.default)
print s # Result: {"_id": {"$oid": "4edebd262ae5e93b41000000"}}
The bson.json_util.object_hook function does not seem to have any type of handling for there being ObjectId() in the actual json string representation.
Solution 2:
There are two problems here:
The string you're attempting to JSON-decode is not JSON, it's the string representation of a Python dictionary. In particular, the problem is that
u'_id'
is not a valid JSON key (JSON keys are quoted strings; the "u" here indicates a Python unicode string, which is meaningless in JSON)json_util.object_hook
doesn't makeObjectId
available to JSON; thejson
module will decode the JSON, and then call theobject_hook
callback with each decoded object.json_util.object_hook
will look for certain patterns as defined in the strict mode of MongoDB Extended JSON.
See @jdi's answer for examples of how to properly use json_util
.