sim*_*mao 14 python json simplejson
我使用带有simplejson的Python将多个嵌套字典序列化为JSON.
有没有办法自动排除空/空值?
例如,序列化:
{
"dict1" : {
"key1" : "value1",
"key2" : None
}
}
Run Code Online (Sandbox Code Playgroud)
至
{
"dict1" : {
"key1" : "value1"
}
}
Run Code Online (Sandbox Code Playgroud)
使用Jackson和Java时,您可以使用它Inclusion.NON_NULL来执行此操作.有一个简单的json等价物吗?
Chr*_*gan 18
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
Run Code Online (Sandbox Code Playgroud)
样品用法:
>>> mydict = {'dict1': {'key1': 'value1', 'key2': None}}
>>> print(del_none(mydict.copy()))
{'dict1': {'key1': 'value1'}}
Run Code Online (Sandbox Code Playgroud)
然后你可以喂它json.
小智 10
>>> 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'}}
>>>
Run Code Online (Sandbox Code Playgroud)
我不喜欢del一般使用,更改现有字典可能会产生微妙的效果,具体取决于它们的创建方式.使用None删除创建新词典可以防止所有副作用.
我的 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
Run Code Online (Sandbox Code Playgroud)
例如:
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))
Run Code Online (Sandbox Code Playgroud)
结果如下:
{
'b': 'notNone',
'c': ['hello', 'goodbye'],
'd': [
{
'a': 'notNone',
'c': ['hello', 'goodbye']
},
{
'a': 'notNone',
'c': ['hello', 'goodbye']
}
]
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
15132 次 |
| 最近记录: |