#嵌套json/dict排序
def dict_ordered(obj):
if isinstance(obj, dict):
return sorted((k, dict_ordered(v)) for k, v in obj.items())
if isinstance(obj, list):
return sorted(dict_ordered(x) for x in obj)
else:
return obj
#递归删除json/dict中的某个值
def dict_del(key,obj):
if isinstance(obj, dict):
if key in obj:
obj.pop(key)
for k, v in obj.items():
dict_del(key,v)
if isinstance(obj, list):
for x in obj:
dict_del(key,x)
else:
pass
return obj
#判断json/dict中是否存在某个key
def dict_has_key(key,obj):
if isinstance(obj, dict):
for k, v in obj.items():
if k == key:
return True
else:
ret = dict_has_key(key,v)
if ret:
return True
elif isinstance(obj, list):
for x in obj:
ret = dict_has_key(key,x)
if ret:
return True
else:
pass
if __name__ == '__main__':
tester = {
"base_config":{
"enforce":{
"value":"0",
"inherit":"0",
"global":"0"
},
"modify":{
"value":"0",
"inherit":"0",
"global":"0"
}
},
"safe_control_list":{
"list":[
{
"gid":"0",
"gname":"全网计算机",
"isactive":"1",
"rule_id":"0",
"rule_name":"请选择规则",
"time_range":"所有时间",
"time_range_id":"1",
"policy_tpl":"33",
"policy_tpl_id":"17",
"isonline":"3",
"priority":"1"
}
]
}
}
print(dict_has_key("rule_id",tester))
print(dict_del("policy_tpl_id",tester))
print(dict_ordered(tester))