這是我的JSON文件的樣本:從JSON文件過濾出所需的數據(Python)的
{
"pops": [{
"name": "pop_a",
"subnets": {
"Public": ["1.1.1.0/24,2.2.2.0/24"],
"Private": ["192.168.0.0/24,192.168.1.0/24"],
"more DATA":""
}
},
{
"name": "pop_b",
"subnets": {
"Public": ["3.3.3.0/24,4.4.4.0/24"],
"Private": ["192.168.2.0/24,192.168.3.0/24"],
"more DATA":""
}
}
]
}
後,我讀它,我想打一個DIC對象和存儲的一些事情,我需要從這個文件。 我希望我的對象是這樣..
[{
"name": "pop_a",
"subnets": {"Public": ["1.1.1.0/24,2.2.2.0/24"],"Private": ["192.168.0.0/24,192.168.1.0/24"]}
},
{
"name": "pop_b",
"subnets": {"Public": ["3.3.3.0/24,4.4.4.0/24"],"Private": ["192.168.2.0/24,192.168.3.0/24"]}
}]
的話,我希望能夠進入一些公共/私有值的
這裏是我想,我知道有更新( ),這也給了同樣的不想要的結果
def my_funckion():
nt_json = [{'name':"",'subnets':[]}]
Pname = []
Psubnet= []
for pop in pop_json['pops']: # it print only the last key/value
nt_json[0]['name']= pop['name']
nt_json[0]['subnet'] = pop['subnet']
pprint (nt_json)
for pop in pop_json['pops']:
"""
it print the names in a row then all of the ipss
"""
Pname.append(pop['name'])
Pgre.append(pop['subnet'])
nt_json['pop_name'] = Pname
nt_json['subnet']= Psubnet
pprint (nt_json)
你究竟想要輸出明智嗎?你得到了什麼 – depperm
你不需要格式化JSON文件後,將其導入到變量。只需使用for循環找到您想要的密鑰即可。然後使用嵌套for循環來查找嵌套字典中的鍵。 –
第二個數據結構看起來非常像我的第一個數據結構 - 所以,你需要改變什麼? –