Reputation:
I am parsing a JSON file with Python. One of they keys I am trying to parse has a float
value, and I am getting the following error: TypeError: list indices must be integers, not str
. Below is the code, JSON, and full traceback.
Code:
import json
with open('output.json') as f:
data = json.load(f)
for host in data['ASSET_DATA_REPORT']['HOST_LIST']['HOST']:
print(host['VULN_INFO_LIST']['VULN_INFO']['CVSS_FINAL'])
JSON:
{
"ASSET_DATA_REPORT":{
"HOST_LIST":{
"HOST":[
{
"IP":{
"network_id":"0"
},
"TRACKING_METHOD":"EC2",
"ASSET_TAGS":{
"ASSET_TAG":[
"EC2 Running",
"IF - Database - MySQL"
]
},
"DNS":"i-xxxxxxx",
"EC2_INSTANCE_ID":"i-xxxxxx",
"EC2_INFO":{
"PUBLIC_DNS_NAME":"ec2-xxxxxxxx.amazonaws.com",
"IMAGE_ID":"ami-xxxxxx",
"VPC_ID":"vpc-xxxxxx",
"INSTANCE_STATE":"RUNNING",
"PRIVATE_DNS_NAME":"ip-xxxx.ec2.internal",
"INSTANCE_TYPE":"m3.xlarge"
},
"VULN_INFO_LIST":{
"VULN_INFO":[
{
"CVSS_FINAL":"3.6"
}
]
}
}
]
}
}
}
Traceback:
Traceback (most recent call last):
File "json_format.py", line 11, in <module>
print(host['VULN_INFO_LIST']['VULN_INFO']['CVSS_FINAL'])
TypeError: list indices must be integers, not str
Upvotes: 1
Views: 615
Reputation: 6543
The dictionary containing the "CVSS_FINAL" key is actually itself in a list. Try:
print(host['VULN_INFO_LIST']['VULN_INFO'][0]['CVSS_FINAL'])
As an aside, if you want to store this value as type float in Python (rather than string), you could do:
value = float(host['VULN_INFO_LIST']['VULN_INFO'][0]['CVSS_FINAL'])
Upvotes: 3