在 Python 中,JSON 解析为列表视图仅显示最后一个 JSON 值,总计 5



我一直在解析 URL API,在社区的一些帮助下,我现在能够通过以下 Python 编译获得有序列表:

.py计划:

import urllib, json
url = "http://www.cvedetails.com/json-feed.php?numrows=5&vendor_id=26&product_id=0&version_id=0&hasexp=1&opec=1&opov=1&opcsrf=1&opfileinc=1&opgpriv=0&opsqli=1&opxss=0&opdirt=0&opmemc=0&ophttprs=0&opbyp=0&opginf=0&opdos=0&orderby=0&cvssscoremin=0"
response = urllib.urlopen(url)
data = json.loads(response.read())
for index, entry in enumerate(data, 1):
   print ('Item {}'.format(index))
for name, value in entry.items():
   print '{}: {}'.format(name, value)`

CLI 中的输出:

Item 1 **<-Unpopulated**
Item 2 **<-Unpopulated**
Item 3 **<-Unpopulated**
Item 4 **<-Unpopulated**
Item 5 **<-Populated**
update_date: 2014-01-17
cve_id: CVE-2013-3906
exploit_count: 1
summary: GDI+ in Microsoft Windows Vista SP2 and Server 2008 SP2; Office 2003 SP3, 2007 SP3, and 2010 SP1 and SP2; Office Compatibility Pack SP3; and Lync 2010, 2010 Attendee, 2013, and Basic 2013 allows remote attackers to execute arbitrary code via a crafted TIFF image, as demonstrated by an image in a Word document, and exploited in the wild in October and November 2013.
url: http://www.cvedetails.com/cve/CVE-2013-3906/
publish_date: 2013-11-06
cvss_score: 9.3
cwe_id: 94`

但是,我遇到了一个问题,它只显示JSON请求的最后一个响应。此 API 端点配置为输出 5 个项目,并在我使用 cURL 命令查询它时输出。但是,当我使用上述方法在 Python 中创建列表时,情况并非如此。

谁能帮我解决这个问题?这可能是我缺少的基本东西。

你只在最后执行第二个循环,这就是为什么你只得到一个项目。你应该把第二个循环放在第一个循环中,这样你就会遍历你得到的每个entry

for index, entry in enumerate(data, 1):
    print ('Item {}'.format(index))
    for name, value in entry.items():
        print '{}: {}'.format(name, value)`

最新更新