Unable to deserialize PyMongo ObjectId from JSON

前端 未结 2 821
小蘑菇
小蘑菇 2020-12-05 20:34

I\'m seemingly unable to deserialize my MongoDB JSON document with the BSON json_util.

The json.loads function is choking on the ObjectId() string. I h

2条回答
  •  渐次进展
    2020-12-05 21:17

    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.

提交回复
热议问题