1. 程式人生 > 實用技巧 >讀取json資料輸入鍵拿到對應的值【多測師_王sir】

讀取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')