Python jsonpickle错误: 'OrderedDict' object has no attribute '_OrderedDict__root'

标签 python attributeerror ordereddictionary jsonpickle

当我尝试pickle一个相当复杂的对象时,我遇到了这个异常,不幸的是我不知道如何在这里描述。我知道这很难说太多,但就其值(value)而言:

>>> frozen = jsonpickle.encode(my_complex_object_instance)
>>> thawed = jsonpickle.decode(frozen)

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Library/Python/2.7/site-packages/jsonpickle/__init__.py",
  line 152, in decode
    return unpickler.decode(string, backend=backend, keys=keys)
      :
      :
  File "/Library/Python/2.7/site-packages/jsonpickle/unpickler.py",
  line 336, in _restore_from_dict
    instance[k] = value
  File "/Library/Python/2.7/site-packages/botocore/vendored/requests/packages/urllib3/packages/ordered_dict.py",
  line 49, in __setitem__
    root = self.__root
AttributeError: 'OrderedDict' object has no attribute '_OrderedDict__root'

在谷歌搜索该错误时,我没有找到太多帮助。我确实看到,对于更简单的对象来说,同样的问题在过去的某个时间已经得到解决:

https://github.com/jsonpickle/jsonpickle/issues/33

该报告中引用的示例对我有用:

>>> jsonpickle.decode(jsonpickle.encode(collections.OrderedDict()))
OrderedDict()
>>> jsonpickle.decode(jsonpickle.encode(collections.OrderedDict(a=1)))
OrderedDict([(u'a', 1)])

有没有人自己遇到过这个问题并找到解决方案?我询问时表示理解,我的案例可能与另一个已知的例子“不同寻常”。

最佳答案

当我 .decode() 时,我的请求模块似乎遇到了问题。稍微查看了一下 jsonpickle 代码后,我决定 fork 它并更改以下行以查看发生了什么(并且我最终保留了 jsonpickle 的私有(private)副本以及所做的更改,以便我可以继续前进)。

在 jsonpickle/unpickler.py 中(在我的版本中为第 368 行),在方法 _restore_from_dict() 中搜索 if 语句部分:

if (util.is_noncomplex(instance) or
    util.is_dictionary_subclass(instance)):
    instance[k] = value
else:
    setattr(instance, k, value)

并将其更改为此(它将记录失败的错误,然后您可以保留代码或更改具有 __root 的 OrderedDict 版本)

if (util.is_noncomplex(instance) or
    util.is_dictionary_subclass(instance)):
    # Currently requests.adapters.HTTPAdapter is using a non-standard
    # version of OrderedDict which doesn't have a _OrderedDict__root
    # attribute
    try:
        instance[k] = value
    except AttributeError as e:
        import logging
        import pprint
        warnmsg = 'Unable to unpickle {}[{}]={}'.format(pprint.pformat(instance), pprint.pformat(k), pprint.pformat(value))
        logging.error(warnmsg)
else:
    setattr(instance, k, value)

关于Python jsonpickle错误: 'OrderedDict' object has no attribute '_OrderedDict__root' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42098510/

相关文章:

访问 OrderedDict 记录时出现 python Unicode 解码错误

python - 如何调整SVM的参数以获得更好的训练

python - 带有 tox : how to test multiple Python environments? 的简单 Python 项目的 CircleCI

python 错误: 'str' object has no attribute 'upper()'

python - 使用 BeautifulSoup 时出现 AttributeError

python - 如何获得书 "Web Scraping with Python: Collecting Data from the Modern Web"第 7 章数据标准化部分中的相同结果

python - pandas 按 3 个变量分组,但对其中 2 个变量求和

非字符串的 Python 实习生

python - AttributeError:计算两点之间的距离

python - 查找以相同字符串开头的行并保留最后一次出现