Unable to deserialize PyMongo ObjectId from JSON

前端 未结 2 816
小蘑菇
小蘑菇 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:20

    There are two problems here:

    1. 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)

    2. json_util.object_hook doesn't make ObjectId available to JSON; the json module will decode the JSON, and then call the object_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.

提交回复
热议问题