I am parsing a large amount of json files where I'm converting certain list values into arrays.
For example, for the following json this code turns the "Statement" and "Resource" into an Array.
print(response['PVersion']['Document'])
{
"Version": "---",
"Statement": {
"Effect": "---",
"Action": "---",
"Resource": "*"
}
}
if (type(response['PVersion']['Document']['Statement'])==list):
pass
else:
response['PVersion']['Document']['Statement']=[response['PVersion']['Document']['Statement']]
for elem in response['PVersion']['Document']['Statement']:
if(type(elem['Resource'])==list):
pass
else:
elem['Resource']=[elem['Resource']]
print(response['PVersion']['Document'])
Output:
{
"Version": "---",
"Statement": [{
"Effect": "---",
"Action": "---",
"Resource": ["*"]
}]
}
The same Python code has trouble with the following json file:
print(response['PVersion']['Document'])
{
"Statement": [{
"Action": [
"---"
],
"Resource": "*"
},
{
"Action": [
"---"
],
"Resource": [
"*"
]
},
{
"Effect": "---",
"Resource": [
"*"
]
},
{
"Effect": "---",
"Resource": [
"*"
]
},
{
"Effect": "---",
"Resource": "*"
},
{
"Effect": "---",
"Action": [
"---"
]
},
{
"Effect": "---",
"Action": [
"---"
],
"Resource": "*"
},
{
"Effect": "Allow",
"Resource": "*"
}
]
}
With the identical code from the first example I get the following error:
line 59, in <module>
if(type(elem['Resource'])==list):
KeyError: 'Resource'
I tried adding print(elem['Resource']) before this if statement to see which Resource it's referring to.
The output:
*
['*']
['*']
['*']
*
This points to there being a problem with the second to last "Resource", but I don't see anything different with it.
It works on similar files where there's a combination of list and array values but not on this one for some reason.
Any ideas on how I could solve this?
Resourcekey, which might be raising theKeyError