Skip to content Skip to sidebar Skip to footer

Json.dumps TypeError On Python Dict

The following class is implemented to provide a generic object that can be passed through network as a json-encoded dictionary. I'm actually trying to json encode a dict (!) but it

Solution 1:

You want to make your type a subclass of dict, not of collections.MutableMapping, really.

Even better still, use collections.defaultdict directly instead, it already is a subclass of dict and can be used to implement your tree 'type' easily:

from collections import defaultdict

def Tree():
    return defaultdict(Tree)

tree = Tree()

Demonstration:

>>> from collections import defaultdict
>>> def Tree():
...     return defaultdict(Tree)
... 
>>> tree = Tree()
>>> tree['one']['two'] = 'foobar'
>>> tree
defaultdict(<function Tree at 0x107f40e60>, {'one': defaultdict(<function Tree at 0x107f40e60>, {'two': 'foobar'})})
>>> import json
>>> json.dumps(tree)
'{"one": {"two": "foobar"}}'

If you must add your own methods and behaviour, then I'd subclass defaultdict and build upon that base:

class CustomDict(defaultdict):
    pass

As this is still a subclass of dict, the json library will happily convert that to a JSON object without special handling.


Post a Comment for "Json.dumps TypeError On Python Dict"