![](/img/trans.png)
[英]How do I replace a value of a key from a returned JSON object after calling an API using requests.get?
[英]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
,有两个key
: id
和label
,所以即使你要拿一个特定的元素,比如说 -
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.