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

标签 python json simplejson

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

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

例如,序列化这个:

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

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

将 Jackson 与 Java 结合使用时,您可以使用 Inclusion.NON_NULL 来执行此操作。是否有等效的 simplejson?

最佳答案

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

关于python - 从 JSON 序列化中排除空/空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4255400/

相关文章:

python - simplejson - 编码 regexp\d+

python - 如何使用 opencv2 将 1 channel 图像转换为 3 channel 图像?

java - 具有嵌套值的 JSON 到 POJO

python - 在 OpenShift 上安装 python 包

python - 在 Python 中编辑现有的 JSON

由于 json,PHP 无法加载 Memcached 扩展?

python - 如何在 python3 中取消使用 __setitem__ 验证的 'dict' 的子类?

python - 如何查找字符串中的值、操作和替换它们

python - 如何从 jinja 模板中具有两个键到一个值的字典中删除引号和括号?

json - 如何使用 javascript 将 json 数据写入 google 工作表