Python dict上的json.dumps TypeError

时间:2013-01-31 17:43:46

标签: python json typeerror

实现以下类以提供可以作为json编码的字典通过网络传递的通用对象。我实际上是在尝试json编码一个字典(!),但它不起作用。

我知道它可以使用自定义编码器类,但我不明白为什么在我编码dict时它是必要的。

有人可以解释TypeError或提供一种编码方法而无需继承JSONEncoder吗?

这是不良行为。

>>> def tree(): return CustomDict(tree)
>>> d = tree()
>>> d['one']['test']['four'] = 19
>>> d.dict
{ 'one' : { 'test': {'four': 19}}}
>>> type(d.dict)
<type 'dict'> 
>>> import json
>>> json.dumps(d.dict)
# stacktrace removed
TypeError: {'one': {'test': {'four': 19}}} is not JSON serializable
>>> normal_d = {'one': {'test': {'four': 19}}}
>>> type(normal_d)
<type 'dict'>
>>> json.dumps(normal_d)
"{'one': {'test': {'four': 19}}}"
>>> normal_d == d
True

我希望能够做到以下

>>>> json.dumps(dict(d))
"{'one': {'test': {'four': 19}}}"

但我添加了dict属性'强制它'(显然不起作用)。现在这是一个更大的谜团。以下是CustomDict类的代码

class CustomDict(collections.MutableMapping):                                
    """                                                                         
    A defaultdict-like object that can also have properties and special methods 
    """                                                                         

    def __init__(self, default_type=str, *args,  **kwargs):                     
        """                                                                     
        instantiate as a default-dict (str if type not provided). Try to update 
        self with each arg, and then update self with kwargs.                                                                

        @param default_type: the type of the default dict                       
        @type default_type: type (or class)                                     
        """                                                                     
        self._type = default_type                                               
        self._store = collections.defaultdict(default_type)                     
        self._dict = {}                                                         

        for arg in args:                                                        
            if isinstance(arg, collections.MutableMapping):                     
                self.update(arg)                                                

        self.update(kwargs)                                                     

    @property                                                                   
    def dict(self):                                                             
        return self._dict                                                       

    def __contains__(self, key):                                                
        return key in self._store                                               

    def __len__(self):                                                          
        return len(self._store)                                                 

    def __iter__(self):                                                         
        return iter(self._store)                                                

    def __getitem__(self, key):                                                 
        self._dict[key] = self._store[key]                                      
        return self._store[key]                                                 

    def __setitem__(self, key, val):                                            
        self._dict[key] = val                                                   
        self._store[key] = val                                                  

    def __delitem__(self, key):                                                 
        del self._store[key]                                                    

    def __str__(self):                                                          
        return str(dict(self._store))   

1 个答案:

答案 0 :(得分:1)

您希望将您的类型设为dict的子类,而不是collections.MutableMapping的子类。

更好的是,直接使用collections.defaultdict,它已经是dict的子类,可以用来轻松实现树的“类型”:

from collections import defaultdict

def Tree():
    return defaultdict(Tree)

tree = Tree()

演示:

>>> 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"}}'

如果你必须添加自己的方法和行为,那么我将继承defaultdict并在此基础上构建:

class CustomDict(defaultdict):
    pass

由于它仍然是dict的子类,json库很乐意将其转换为JSON对象而无需特殊处理。