I am trying to get the values from JSON which is nested.
response = {
"Instance":[
{
"id":"id-1",
"Tags":[],
},
{
"id":"id-2",
"Tags":[],
},
{
"id":"id-3",
"Tags":[
{
"Key":"test",
"Value":"test"
}
],
}
]
}
and the python code i tried is
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 ")
I am trying to parse through all ids and get the tags that contain the test key. But getting error in 3rd loop when tags has some values. Error in exception is just telling 'Tags' How can I modify the code?
CodePudding user response:
You are testing for the presence of the key "Tags"
in the identifier
dict as follows:
if identifier["Tags"]:
# iterate over identifier["Tags"]
If "Tags"
is not present in the identifier
dict, this will result in:
KeyError: 'Tags'
Instead, you should use:
if "Tags" in identifier:
# iterate over identifier["Tags"]