无法从JSON反序列化PyMongo ObjectId [英] Unable to deserialize PyMongo ObjectId from JSON

查看:288
本文介绍了无法从JSON反序列化PyMongo ObjectId的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我似乎无法使用BSON反序列化我的MongoDB JSON文档 json_util .

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

json.loads函数阻塞了ObjectId()字符串.我了解json_util能够处理MongoDB的ObjectId格式并将其转换为可用的JSON.

The json.loads function is choking on the ObjectId() string. I had understood json_util capable of handling MongoDB's ObjectId format and transforming into usable 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表示形式...

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"}}

bson.json_util.object_hook函数似乎没有任何类型的处理,因为在实际的json字符串表示中存在ObjectId().

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.

这篇关于无法从JSON反序列化PyMongo ObjectId的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆