Python字典中json.dumps的TypeError错误

1 投票
1 回答
5125 浏览
提问于 2025-04-17 14:20

下面这个类是用来提供一个通用对象的,可以通过网络以json格式传递一个字典。我其实是想把一个字典转成json格式,但它就是不行。

我知道用自定义的编码器类是可以的,但我不明白为什么在我只是想编码一个字典的时候,这么做是必要的。

有没有人能解释一下这个类型错误,或者给我一个不需要继承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}}}"

但是我加了字典属性来“强制”它(显然没用)。现在这变得更加神秘了。这里是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 个回答

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 对象,而不需要特别处理。

撰写回答