我正在创建一个Python脚本来解析来自https://vulners.com/api/v3/search/stats/
的JSON响应我的.py中有以下代码:
import json
import requests
response = requests.get('https://vulners.com/api/v3/search/stats/')
vuln_set = json.loads(response.text)
vuln_type = vuln_set['data']['type_results']
vuln_bulletinfamily = vuln_set['data']['type_results'][vuln_type]['bulletinFamily']
vuln_name = vuln_set['data']['type_results'][vuln_type]['displayName']
print("Type: " + vuln_type)
print("Bulletin Family: " + vuln_bulletinfamily)
print("Name: " + vuln_name)
我需要获取vuln_type以及子信息(vuln_bulletinfamily& vuln_name) JSON响应的摘录:
"data": {
"type_results": {
"aix": {
"lastUpdated": [],
"bulletinFamily": "unix",
"displayName": "IBM AIX",
"lastrun": "2017-09-14T14:04:56",
"count": 110,
"workTime": "0:00:10.983795"
},
"akamaiblog": {
"lastUpdated": [],
"bulletinFamily": "blog",
"displayName": "Akamai Blog",
"lastrun": "2017-09-14T10:38:52",
"count": 1463,
"workTime": "0:00:00.358691"
},
"amazon": {
"lastUpdated": [],
"bulletinFamily": "unix",
"displayName": "Amazon Linux AMI",
"lastrun": "2017-09-14T14:17:40",
"count": 889,
"workTime": "0:00:01.839594"
},
我收到TypeError的错误:unhashable类型:' dict'
回溯:
Traceback (most recent call last):
File "test.py", line 9, in <module>
vuln_bulletinfamily = vuln_set['data']['type_results'][vuln_type]['bulletinFamily']
TypeError: unhashable type: 'dict'
答案 0 :(得分:1)
在追溯线,下一行和第一个打印行中,您尝试使用也是字典的键访问字典type_results
和vuln_type
。
您需要循环键,例如: -
import json
import requests
response = requests.get('https://vulners.com/api/v3/search/stats/')
vuln_set = json.loads(response.text)
vuln_type = vuln_set['data']['type_results']
for k in vuln_type :
vuln_bulletinfamily = vuln_set['data']['type_results'][k]['bulletinFamily']
vuln_name = vuln_set['data']['type_results'][k]['displayName']
print("Type: " + k)
print("Bulletin Family: " + vuln_bulletinfamily)
print("Name: " + vuln_name)
答案 1 :(得分:0)
vuln_set = json.loads(response.text) vs response.json()