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

新手上路,请多包涵

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

有什么方法可以自动排除空/空值吗?

例如,序列化这个:

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

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

将 Jackson 与 Java 一起使用时,您可以使用 Inclusion.NON_NULL 来执行此操作。是否有一个 simplejson 等价物?

原文由 simao 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.2k
2 个回答
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

原文由 Chris Morgan 发布,翻译遵循 CC BY-SA 3.0 许可协议

我的 Python3 版本的好处是不更改输入,以及递归到嵌套在列表中的字典:

 def clean_nones(value):
    """
    Recursively remove all None values from dictionaries and lists, and returns
    the result as a new dictionary or list.
    """
    if isinstance(value, list):
        return [clean_nones(x) for x in value if x is not None]
    elif isinstance(value, dict):
        return {
            key: clean_nones(val)
            for key, val in value.items()
            if val is not None
        }
    else:
        return value

例如:

 a = {
    "a": None,
    "b": "notNone",
    "c": ["hello", None, "goodbye"],
    "d": [
        {
            "a": "notNone",
            "b": None,
            "c": ["hello", None, "goodbye"],
        },
        {
            "a": "notNone",
            "b": None,
            "c": ["hello", None, "goodbye"],
        }
    ]
}

print(clean_nones(a))

结果是:

 {
    'b': 'notNone',
    'c': ['hello', 'goodbye'],
    'd': [
        {
            'a': 'notNone',
            'c': ['hello', 'goodbye']
        },
        {
            'a': 'notNone',
            'c': ['hello', 'goodbye']
        }
    ]
}

原文由 MatanRubin 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题