如何将DictProxy对象转换为JSON可序列化的dict?

kak*_*kyo 3 python json dictionary multiprocessing

我有一个用于支持并发的DictProxy对象multiprocessing.Manager().dict().在运行结束时,我需要将dict序列化为JSON.但目前还不清楚如何将其转换为DictProxy可序列化的dict对象.当我尝试它时,我得到了:

TypeError: <DictProxy object, typeid 'dict' at 0x10a240ed0> is not JSON serializable
Run Code Online (Sandbox Code Playgroud)

我怎样才能解决这个问题?

mar*_*eau 13

我不喜欢使用DictProxy类似的私有方法_getvalue(),而是更喜欢使用像公共方法那样copy()返回浅层复制的方法dict.

import multiprocessing

if __name__ == '__main__':
    manager = multiprocessing.Manager()
    d = manager.dict()
    import json
    json.dumps(d.copy())
Run Code Online (Sandbox Code Playgroud)

  • @martineau它仍然显示模型“TypeError: &lt;DictProxy object, typeid 'dict' at 0x10a240ed0&gt; is not JSON Serialized”。 (2认同)

dan*_*ano 5

使用dict_proxy._getvalue()提取实际dict实例的代理底层,并传递到json.dump(或任何你正在使用)。

>>> import multiprocessing
>>> m = multiprocessing.Manager()
>>> d = m.dict()
>>> import json
>>> json.dumps(d)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib64/python2.6/json/__init__.py", line 230, in dumps
    return _default_encoder.encode(obj)
  File "/usr/lib64/python2.6/json/encoder.py", line 367, in encode
    chunks = list(self.iterencode(o))
  File "/usr/lib64/python2.6/json/encoder.py", line 317, in _iterencode
    for chunk in self._iterencode_default(o, markers):
  File "/usr/lib64/python2.6/json/encoder.py", line 323, in _iterencode_default
    newobj = self.default(o)
  File "/usr/lib64/python2.6/json/encoder.py", line 344, in default
    raise TypeError(repr(o) + " is not JSON serializable")
TypeError: <DictProxy object, typeid 'dict' at 0x97eed0> is not JSON serializable
>>> json.dumps(d._getvalue())
'{}'
Run Code Online (Sandbox Code Playgroud)


Ped*_*ito 5

迟到的回答,但我解决了以下错误:

TypeError: Object of type 'DictProxy' is not JSON serializable
TypeError: Object of type 'ListProxy' is not JSON serializable
Run Code Online (Sandbox Code Playgroud)

使用:

from multiprocessing import Manager

manager = Manager()

# For Dicts
x = manager.dict()
json.dumps(dict(x))

# For Lists
x = manager.list()
json.dumps(list(x))
Run Code Online (Sandbox Code Playgroud)