简体   繁体   English

Python JSON 不可散列类型:'dict'

[英]Python JSON unhashable type: 'dict'

I am creating a Python script to parse the JSON response from https://vulners.com/api/v3/search/stats/我正在创建一个 Python 脚本来解析来自https://vulners.com/api/v3/search/stats/的 JSON 响应

I have the following code in my .py:我的 .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)

I need to get the vuln_type aswell as the child information (vuln_bulletinfamily & vuln_name) An excerpt from the JSON response:我需要获取 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"
  },

I am getting an error of TypeError: unhashable type: 'dict'我收到 TypeError 错误:不可散列类型:'dict'

Traceback:追溯:

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'

In the traceback line, the next line and the first print line, you are trying to access a dict type_results and vuln_type with a key that is also a dictionary.在回溯行、下一行和第一个打印行中,您尝试使用一个也是字典的键访问 dict type_resultsvuln_type You need to loop through the keys, like:-您需要遍历键,例如:-

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)
vuln_set = json.loads(response.text) vs response.json()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM