我似乎无法使用BSON json_util反序列化我的MongoDB JSON文档.
json.loads函数在ObjectId()
字符串上窒息.我理解json_util能够处理MongoDB的ObjectId格式并转换为可用的JSON.
Python代码:
import json from bson import json_util s = "{u'_id': ObjectId('4ed559abf047050c58000000')}" u = json.loads(s, object_hook=json_util.object_hook)
我得到解码器异常:
... u = json.loads(s, object_hook=json_util.object_hook) File "\python27\lib\json\__init__.py", line 339, in loads return cls(encoding=encoding, **kw).decode(s) File "\python27\lib\json\decoder.py", line 366, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "\python27\lib\json\decoder.py", line 382, in raw_decode obj, end = self.scan_once(s, idx) ValueError: Expecting property name: line 1 column 1 (char 1)
我错过了什么吗?
我认为你的字符串形式实际上看起来像python表示...
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"}}
对于在实际的json字符串表示中存在ObjectId(),bson.json_util.object_hook函数似乎没有任何类型的处理.