如何使用python从响应中获取特定值



我正试图从JSON中获得嵌套的值。

response = {
"Instance":[
{
"id":"id-1",
"Tags":[],
},
{
"id":"id-2",
"Tags":[],
},
{
"id":"id-3",
"Tags":[
{
"Key":"test",
"Value":"test"
}
],
}
]
}

和我尝试的python代码是

if response["Instance"]:
print("1-->",response["Instance"])
for identifier in response["Instance"]:
print("2-->", identifier)
if identifier["id"]:
print("3-->", identifier["id"])
if identifier["Tags"]:   #ERROR Thrown here as 'Tags' in exception
print("4-->", identifier["Tags"])
for tag in identifier["Tags"]:
print("5-->", identifier["Tags"])
if tag['Key'] == 'test' and tag['Value'] == 'test':
print("6--> test present ")

我试图解析所有id并获得包含测试键的标签。但误差在3日循环标签有一些值。异常中的错误只是告诉'Tags'我如何修改代码?

你测试的关键"Tags"identifierdict类型如下:

if identifier["Tags"]:
# iterate over identifier["Tags"]

如果"Tags"不存在于identifier字典中,这将导致:

KeyError: 'Tags'

应该使用:

if "Tags" in identifier:
# iterate over identifier["Tags"]

最新更新