我創建了一個等于t.json. JSON檔案如下:
{
"groups": {
"customerduy": {
"nonprod": {
"name": "customerduynonprod",
"id": "529646781943",
"owner": "[email protected]",
"manager_email": ""
},
"prod": {
"name": "phishing_duyaccountprod",
"id": "241683454720",
"owner": "[email protected]",
"manager_email": ""
}
},
"customerduyprod": {
"nonprod": {
"name": "phishing_duyaccountnonprod",
"id": "638968214142",
"owner": "[email protected]",
"manager_email": ""
}
},
"ciasuppliergenius": {
"prod": {
"name": "ciasuppliergeniusprod",
"id": "220753788760",
"owner": "[email protected]",
"manager_email": "[email protected]"
}
}
}
}
我的目標是決議這個 JSON 檔案并獲取“所有者”的值并將其輸出到一個新的 var。下面的例子:
t.json = group_map
group_id_aws = group(
group.upper(),
"accounts",
template,
owner = group_map['groups']['prod'],
manager_description = "Groups for teams to access their product accounts.",
我不斷收到的錯誤是: KeyError: 'prod'
uj5u.com熱心網友回復:
Owner 出現了 4 次,所以這里是如何獲得所有這些。
import json
# read the json
with open("C:\\test\\test.json") as f:
data = json.load(f)
# get all 4 occurances
owner_1 = data['groups']['customerduy']['nonprod']['owner']
owner_2 = data['groups']['customerduy']['prod']['owner']
owner_3 = data['groups']['customerduyprod']['nonprod']['owner']
owner_4 = data['groups']['ciasuppliergenius']['prod']['owner']
# print results
print(owner_1)
print(owner_2)
print(owner_3)
print(owner_4)
結果:
[email protected]
[email protected]
[email protected]
[email protected]
uj5u.com熱心網友回復:
你得到一個關鍵錯誤,因為關鍵 'prod' 不在 'groups' 你所擁有的是
group_map['groups']['customerduy']['prod']
group_map['groups']['ciasuppliergenius']['prod']
因此,您必須從樹中的每個元素中提取“所有者”:
def s(d,t):
for k,v in d.items():
if t == k:
yield v
try:
for i in s(v,t):
yield i
except:
pass
print(','.join(s(j,'owner')))
uj5u.com熱心網友回復:
如果您的 JSON 加載到 variable 中data,您可以使用遞回函式處理可能出現在 JSON 檔案中的兩種容器型別(dict 和 list),遞回:
def find_all_values_for_key(d, key, result):
if isinstance(d, dict):
if key in d:
result.append(d[key])
return
for k, v in d.items():
find_all_values_for_key(v, key, result)
elif isinstance(d, list):
for elem in d:
find_all_values_for_key(elem, key, result)
owners = []
find_all_values_for_key(data, 'owner', owners)
print(f'{owners=}')
這使:
owners=['[email protected]', '[email protected]', '[email protected]', '[email protected]']
這樣您就不必擔心中間鍵的名稱,或者一般來說 JSON 檔案的結構。
您的示例中沒有任何串列,但是通過它們遞回到任何具有owner可能“潛伏”在嵌套在 aa 串列元素下某處的鍵的 dict 是微不足道的,因此最好處理未來對 JSON 的潛在更改.
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/451094.html
