返回JSON浮点值

时间:2018-02-23 19:52:02

标签: python json

我正在使用Python解析JSON文件。我尝试解析的其中一个键值为float,我收到以下错误:TypeError: list indices must be integers, not str。下面是代码,JSON和完整的回溯。

代码:

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 (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

1 个答案:

答案 0 :(得分:3)

包含&#34; CVSS_FINAL&#34;的词典key实际上就是一个列表。尝试:

print(host['VULN_INFO_LIST']['VULN_INFO'][0]['CVSS_FINAL'])

顺便说一句,如果你想将这个值存储为Python中的float类型(而不是字符串),你可以这样做:

value = float(host['VULN_INFO_LIST']['VULN_INFO'][0]['CVSS_FINAL'])