我有一个使用 multiprocessing.Manager().dict()
创建的 DictProxy
对象,以支持并发。在运行结束时,我需要将字典序列化为 JSON。但是不清楚如何将 DictProxy
转换为可序列化的字典对象。当我尝试时,得到了以下错误:
TypeError: <DictProxy object, typeid 'dict' at 0x10a240ed0> is not JSON serializable
我该如何修复这个问题?
我有一个使用 multiprocessing.Manager().dict()
创建的 DictProxy
对象,以支持并发。在运行结束时,我需要将字典序列化为 JSON。但是不清楚如何将 DictProxy
转换为可序列化的字典对象。当我尝试时,得到了以下错误:
TypeError: <DictProxy object, typeid 'dict' at 0x10a240ed0> is not JSON serializable
我该如何修复这个问题?
我更喜欢使用公共方法,例如copy()
来代替使用私有的DictProxy
方法,比如_getvalue()
。copy()
会返回一个浅拷贝的dict
。
import multiprocessing
if __name__ == '__main__':
manager = multiprocessing.Manager()
d = manager.dict()
import json
json.dumps(d.copy())
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())
'{}'
d
是空的,如果d
中有一些数据,我认为它会抛出TypeError: <DictProxy object, typeid 'dict' at 0x97eed0> is not JSON serializable
。尝试这段代码 `import multiprocessingif name == 'main':
manager = multiprocessing.Manager()
d = manager.dict()
d['dsd'] = 1
d['b'] = manager.dict()
d['b']['c'] = 1
import json
json.dumps(d._getvalue(), indent=4)` - GoingMyWay虽然回答晚了,但我解决了以下错误:
TypeError: Object of type 'DictProxy' is not JSON serializable
TypeError: Object of type 'ListProxy' is not JSON serializable
使用:
from multiprocessing import Manager
manager = Manager()
# For Dicts
x = manager.dict()
json.dumps(dict(x))
# For Lists
x = manager.list()
json.dumps(list(x))
manager = Manager()
return_dict = manager.dict()
return return_dict.copy()
d.copy()
不起作用。 - GoingMyWayTypeError:<DictProxy object,typeid'dict'at 0x10a240ed0>不可JSON序列化
。 - GoingMyWayTypeError: <DictProxy object, typeid 'dict' at 0x10a240ed0> is not JSON serializable
最简单的方法是使用for循环获取所有数据并保存到普通字典中。 - GoingMyWay