简体   繁体   English

如何使用键从 json 数组中获取值

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

I'm reading a json and want to get the label field with a specific id.我正在阅读 json 并希望获得具有特定 ID 的 label 字段。 What I currently have is:我目前拥有的是:

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"])

My json has data blocks (being "interface" or "settings") and those data blocks contain arrays.我的 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":[
    
    ]
}

You can "find" the element in the interface list via a list-comprehension, and fetch the label from that element.您可以通过列表推导“查找” interface列表中的元素,并从该元素中获取 label。 For instance:例如:

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

If you cannot assume that the relevant id exists, then you can wrap this in a try-except, or you can get a list of the labels and validate that it isn't of length 0, or whatever you think would work best for you.如果你不能假设相关的 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

And while you're at it, you might want to explicitly deal with there being multiple elements with the same id, etc.当你在做的时候,你可能想要明确地处理多个具有相同 id 的元素,等等。


Clarification regarding your error(s): parsed_dict["interface"] is a list, so you can index it with int s (and slices and stuff, but that's besides the point), and not with str ings.关于您的错误的澄清: parsed_dict["interface"]是一个列表,因此您可以使用int s(以及切片和其他东西,但除此之外)而不是str ings 对其进行索引。
Each of the list elements is a dict , with two key s: id and label , so even if you were to take a specific element, say -每个列表元素都是一个dict ,有两个keyidlabel ,所以即使你要拿一个特定的元素,比如说 -

el = parsed_dict["interface"][0]

you still couldn't do el['testkey'] , because that's a value of the dict, not a key .仍然不能做el['testkey'] ,因为那是字典的value ,而不是key

You could check if the id is the one you're looking for though, via -可以检查id是否是您正在寻找的那个,通过 -

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

In fact, the single line I gave above is really just shorthand for running over all the elements with a loop and doing just that...事实上,我上面给出的单行实际上只是用循环遍历所有元素并这样做的简写...

You need to browse through all the values and check if it matches expected value.您需要浏览所有值并检查它是否与预期值匹配。 Because values are not guaranteed to be unique in a dictionary, you can't simply refer to them directly like you do with keys.因为不能保证值在字典中是唯一的,所以不能像使用键那样直接引用它们。

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