读取json数据输入键拿到对应的值【多测师_王sir】
data.json的数据如下: { "name":"中国", "province":[ { "name1":"多测师", "city1":"上海多测师" }, { "name2":"多测师", "city2":"上海多测师" }, { "name3":"多测师", "city3":"上海多测师" }, { "name4":"多测师", "city4":"上海多测师" } ] }
#coding=utf-8 """ =========================== Author:多测师_王sir Time:2020-09-08 13:51 Wechat:xiaoshubass website:www.duoceshi.cn =========================== """ import json new_dict = {} def to_dict(dict1): '''封装一个转换为字典的函数''' for k,v in dict1.items(): if isinstance(v,dict): to_dict(v) elif isinstance(v,list): for j in v: to_dict(j) else: new_dict[k] = v return new_dict def read_json(path): list1=[] dict2={} o = open(path,'r',encoding='utf-8') all = o.read() dict1 = json.loads(all) value = to_dict(dict1) name = input('请输入您想要提取的键:') if name in value: dict2.setdefault(name,value[name]) #如果自己输入的键在字典里面就添加键值对到dict2里面 list1.append(dict2) print(list1) if __name__ == '__main__': read_json('C:\project\dcs6\decorator\data.json')