How to convert a DictProxy object into JSON serializable dict?
Late answer, but I solved the following errors:
TypeError: Object of type 'DictProxy' is not JSON serializable
TypeError: Object of type 'ListProxy' is not JSON serializable
using:
from multiprocessing import Manager
manager = Manager()
# For Dicts
x = manager.dict()
json.dumps(dict(x))
# For Lists
x = manager.list()
json.dumps(list(x))
Use dict_proxy._getvalue()
to fetch the actual dict
instance underlying the proxy, and pass that to json.dump
(or whatever method you're using).
>>> 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())
'{}'
Rather than using a private DictProxy
method like _getvalue()
, I'd prefer using a public one like copy()
which returns a shallowly-copied dict
.
import multiprocessing
if __name__ == '__main__':
manager = multiprocessing.Manager()
d = manager.dict()
import json
json.dumps(d.copy())