I have a DictProxy
object created using multiprocessing.Manager().dict()
to support concurrency. At the end of the run, I need to serialize the dict to JSON. But it's unclear how to convert the DictProxy
to serializable dict object. When I tried it, I got:
TypeError: <DictProxy object, typeid 'dict' at 0x10a240ed0> is not JSON serializable
How can I fix this?
Use toJSON() Method to make class JSON serializable So we don't need to write custom JSONEncoder. This new toJSON() serializer method will return the JSON representation of the Object. i.e., It will convert custom Python Object to JSON string.
The json module exposes two methods for serializing Python objects into JSON format. dump() will write Python data to a file-like object. We use this when we want to serialize our Python data to an external JSON file. dumps() will write Python data to a string in JSON format.
1) Using dumps() function Python possesses a default module, 'json,' with an in-built function named dumps() to convert the dictionary into a JSON object by importing the "json" module. "json" module makes it easy to parse the JSON strings which contain the JSON object.
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())
'{}'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With