需求:输入以下json串,返回字典,字典值仅包括json最底层数据
输入:my_dict = {
"name":"alien",
"country":"china",
"other":{
"age":"18",
"gender":"man"
},
"school":"HLW"
}
输出:{‘country‘: ‘china‘, ‘school‘: ‘HLW‘, ‘age‘: ‘18‘, ‘name‘: ‘alien‘, ‘gender‘: ‘man‘}
1、 背景知识
1)item(),遍历字典
2)isinstance(),判断对象的变量类型
2、思路
获取json中key和value值,判断如果value是不是字典类型,则循环递归获取key和value值
3、获取json最底层数据(一)
def read_json_only1(dict_str): dict_result = {} for k,v in dict_str.items(): if isinstance(v,dict): #判断如果value是字典类型,则提取字典中的key和value for k2,v2 in v.items(): dict_result[k2]=v2 else: dict_result[k] = v print dict_result if __name__ == ‘__main__‘: read_json_only1(my_dict)
输入:
my_dict = {
"name":"alien",
"country":"china",
"other":{
"age":"18",
"gender":"man"
},
"school":"HLW"
}
输出:{‘country‘: ‘china‘, ‘school‘: ‘HLW‘, ‘age‘: ‘18‘, ‘name‘: ‘alien‘, ‘gender‘: ‘man‘}
4、发现上面方法只能满足只有一到两层的情况,如果两层下面的value 还是字典,就没法获取到,于是打个问号,能否用递归方法实现
如:输入串为
my_dict = {
"name":"alien",
"country":"china",
"other":{
"age":"18",
"gender":"man",
"other":{
"address":"beijing",
"phone":"13800138000"
}
},
"school":"HLW"
}
输出结果为:{‘school‘: ‘HLW‘, ‘name‘: ‘alien‘, ‘country‘: ‘china‘, ‘age‘: ‘18‘, ‘other‘: {‘phone‘: ‘13800138000‘, ‘address‘: ‘beijing‘}, ‘gender‘: ‘man‘}
5、优化,使用递归获取获取json最底层数据(二)
dict_result = {} def read_json_only(dict_str): for k,v in dict_str.items(): if isinstance(v, dict): read_json_only(v) else: dict_result[k] = v return dict_result if __name__ == ‘__main__‘: print read_json_only(my_dict)
输出:{‘school‘: ‘HLW‘, ‘name‘: ‘alien‘, ‘country‘: ‘china‘, ‘age‘: ‘18‘, ‘phone‘: ‘13800138000‘, ‘gender‘: ‘man‘, ‘address‘: ‘beijing‘}
注意,for循环过程return只返回第一次满足条件的结果,会出现其余的没有返回的问题。