学习json中,需要删除嵌套json中value为空(包含'', {},[], null)的key并返回去除后的json。如果是json中没有嵌套
data = {'name': 'Jack', 'mobile': '12345678911', 'address': '', 'ID': '', }
则可以使用如下语句:
for k in data.keys():
if not data[k]:
del data[k]
因为在python3中dict.keys()是一个迭代器。迭代器在操作过程中,是不允许被修改的。所以我们要把迭代器(data.keys()),改为一个list(非迭代器),这样我们就可以对字典操作了。其实这里我们通过list()已经把for循环迭代的对象,由原来的data.keys()变为了一个由data.keys()组成的一个list()数据了。
但如果是嵌套的情况,则上述方法不再适合,但是逻辑较为通用
data = {
"first_ name": "Jane",
"last_ name": "Smith",
"email": "jane .smith@wyng.com",
"gender": "null",
"gender1": " ",
"gender2": "",
"invitations": [
{
"from": "1",
"code": "null"
}
],
"company": {
"name": "",
"industries": []
},
"address": {
"city": "New York",
"state": "NY",
"zip": "10011",
"street": ""
}
}
但如果是嵌套的语句的话
def remove_empty_key(info):
if isinstance(info, dict):
info_re = dict()
for key, value in info.items():
if isinstance(value, dict) or isinstance(value, list):
re = remove_empty_key(value)
if len(re):
info_re[key] = re
elif type(value) == str and value not in ['', {}, [], 'null']:
info_re[key] = value
return info_re
elif isinstance(info, list):
info_re = list()
for value in info:
if isinstance(value, dict) or isinstance(value, list):
re = remove_empty_key(value)
if len(re):
info_re.append(re)
elif type(value) == str and value not in ['', {}, [], 'null']:
info_re.append(value)
return info_re
else:
print('输入非列表/字典')
此时如果打印则不是按照json格式打印出来,因此使用如下格式进行打印
print json.dumps(data, sort_keys=True, indent=2)
那如果是想按照原来的json顺序进行输出的话,则需要在定义字典的时候
from collections import OrderedDict
同时将字典定义为如下:
new_info = OrderedDict()