我正在使用 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/