从JSON序列化中排除空/空值

2024-05-13 19:20:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用带有simplejson的Python将多个嵌套字典序列化为JSON。

有没有办法自动排除空值/空值?

例如,序列化:

 {
     "dict1" : {
     "key1" : "value1",
     "key2" : None
     }
 }

 {
     "dict1" : {
     "key1" : "value1"
     }
 }

在Java中使用Jackson时,可以使用Inclusion.NON_NULL来完成这项工作。有一个simplejson等价物吗?


Tags: nonejson字典序列化java空值simplejsonkey2
3条回答
def del_none(d):
    """
    Delete keys with the value ``None`` in a dictionary, recursively.

    This alters the input so you may wish to ``copy`` the dict first.
    """
    # For Python 3, write `list(d.items())`; `d.items()` won’t work
    # For Python 2, write `d.items()`; `d.iteritems()` won’t work
    for key, value in list(d.items()):
        if value is None:
            del d[key]
        elif isinstance(value, dict):
            del_none(value)
    return d  # For convenience

示例用法:

>>> mydict = {'dict1': {'key1': 'value1', 'key2': None}}
>>> print(del_none(mydict.copy()))
{'dict1': {'key1': 'value1'}}

然后您可以将其馈送给json

def excludeNone(d):
    for k in list(d):
        if k in d:
            if type(d[k]) == dict:
                excludeNone(d[k])
            if not d[k]:
                del d[k]
>>> def cleandict(d):
...     if not isinstance(d, dict):
...         return d
...     return dict((k,cleandict(v)) for k,v in d.iteritems() if v is not None)
... 
>>> mydict = dict(dict1=dict(key1='value1', key2=None))
>>> print cleandict(mydict)
{'dict1': {'key1': 'value1'}}
>>> 

我不喜欢使用del一般来说,更改现有字典可能会产生微妙的影响,这取决于它们是如何创建的。创建删除了None的新词典可以防止所有副作用。

相关问题 更多 >