2017-09-14 77 views
1

我創建一個Python腳本解析從https://vulners.com/api/v3/search/stats/Python的JSON unhashable類型:「字典」

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" 
    }, 

我GE擬合類型錯誤的錯誤:unhashable類型:「字典」

回溯:

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' 
+1

密鑰必須是可散列的。作爲一般規則,只有不可變對象(字符串,整數,浮點數,frozensets,不可變元組)是可散列的(儘管例外是可能的)。 – amrit

+0

我已將traceback添加到上述 – Luke

+1

您正在傳遞一個字典,以查找爲字典密鑰。 'vuln_type = vuln_set ['data'] ['type_results']',它是一個字典嘗試打印它。您需要從該詞典中選擇一個可能的鍵來繼續深入到「bulletinFamily」的層次結構中。目前還不清楚你想要做什麼,也許你打算迭代'type_results'字典中的項目? –

回答

1

在回溯線,下一行和打印的第一行,你試圖訪問一個字典type_resultsvuln_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) 
+0

工作正常!幾天前我剛剛開始使用python,來自PHP – Luke

相關問題