代码之家  ›  专栏  ›  技术社区  ›  simao

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

  •  12
  • simao  · 技术社区  · 14 年前

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

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

    例如,序列化:

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

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

    在Java中使用Jackson时 Inclusion.NON_NULL 做这个。有一个simplejson等价物吗?

    3 回复  |  直到 8 年前
        1
  •  18
  •   Chris Morgan    7 年前
    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 .

        2
  •  10
  •   fragilewindows Mircea Mihai    8 年前
    >>> 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 移除可防止所有副作用。

        3
  •  0
  •   utapyngo    14 年前
    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]
    
    推荐文章