从JSON序列化中排除空值/空对象
我正在用Python和simplejson把多个嵌套的字典转换成JSON格式。
有没有什么方法可以自动排除空值或空的内容呢?
比如,把这个:
{
"dict1" : {
"key1" : "value1",
"key2" : None
}
}
转换成这个:
{
"dict1" : {
"key1" : "value1"
}
}
在Java中使用Jackson时,可以用Inclusion.NON_NULL
来实现这个功能。那在simplejson中有没有类似的做法呢?
9 个回答
12
>>> 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
,可以避免所有这些副作用。
25
我这个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']
}
]
}
30
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
。