在尝试腌制一个相当复杂的对象时,我用jsonpickle碰到了这个异常,不幸的是,我不确定如何在此处进行描述。我知道这很难说很多话,但是值得:

>>> 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代码之后,我决定将其分叉并更改以下行以查看发生了什么(并且我最终保留了所做更改的jsonpickle的私有副本,以便继续前进)。

在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)

10-02 10:41