簡體   English   中英

如何使用鍵從 json 數組中獲取值

[英]How do I get a value from a json array using a key

我正在閱讀 json 並希望獲得具有特定 ID 的 label 字段。 我目前擁有的是:

with open("local_en.json") as json_file:
    parsed_dict = json.load(json_file)
    print(parsed_dict)                         # works
    print(parsed_dict["interface"])            # works
    print(parsed_dict["interface"]["testkey"])

我的 json 有數據塊(作為“界面”或“設置”),這些數據塊包含 arrays。

{
    "interface":[
    {"id": "testkey", "label": "The interface block local worked!"}
    {"id": "testkey2", "label": "The interface block local worked, AGAIN!"}
    ],
    "settings":[
    
    ],
    "popup_success":[
        
    ],
    "popup_error":[
    
    ],
    "popup_warning":[
    
    ],
    "other_strings":[
    
    ]
}

您可以通過列表推導“查找” interface列表中的元素,並從該元素中獲取 label。 例如:

label = [x['label'] for x in parsed_dict['interface'] if x['id'] == 'testkey'][0]

如果你不能假設相關的 id 存在,那么你可以將它包裝在一個 try-except 中,或者你可以獲得一個標簽列表並驗證它的長度不是 0,或者你認為最適合你的任何東西.

key = 'testkey'
labels = [x['label'] for x in parsed_dict['interface'] if x['id'] == key]
assert len(labels) > 0, f"There's no matching element for key {key}"
label = labels[0]  # Takes the first if there are multiple such elements in the interface array

當你在做的時候,你可能想要明確地處理多個具有相同 id 的元素,等等。


關於您的錯誤的澄清: parsed_dict["interface"]是一個列表,因此您可以使用int s(以及切片和其他東西,但除此之外)而不是str ings 對其進行索引。
每個列表元素都是一個dict ,有兩個keyidlabel ,所以即使你要拿一個特定的元素,比如說 -

el = parsed_dict["interface"][0]

仍然不能做el['testkey'] ,因為那是字典的value ,而不是key

可以檢查id是否是您正在尋找的那個,通過 -

if el['id'] == 'testkey':
    print('Yup, this is it')
    label = el['label']

事實上,我上面給出的單行實際上只是用循環遍歷所有元素並這樣做的簡寫...

您需要瀏覽所有值並檢查它是否與預期值匹配。 因為不能保證值在字典中是唯一的,所以不能像使用鍵那樣直接引用它們。

print([el for el in d["interface"] if "testkey" in el.values()])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM