Python JSON 如何过滤返回的数据

2024-05-18 06:34:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用Discogs API获取数据,我想将JSON限制为只有格式为“CD”、“Album”或“Maxi Single”的记录。我不知道如何过滤获取的数据,因为Discogs没有一种更简单的方法从初始请求本身过滤这些数据。您会注意到下面提到的JSON URL有“DVD”和“VHS”,我想省略它们。有什么想法/线索可以在抓取完成后过滤它吗?

JSON URL:http://api.discogs.com/database/search?sort=year&sort_order=asc&artist=Britney+Spears&track=Crazy+Stop+Remix&type=master

Python

url = 'http://api.discogs.com/database/search?sort=year&sort_order=asc&artist=Britney+Spears&track=Crazy+Stop+Remix&type=master'
request = urllib2.Request(url)
request.add_header('User-Agent','Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)')
request.add_header('Content-Type','application/json')
response = urllib2.urlopen(request)
json_object = json.load(response)
if json_object['results'] == []:
    print 'No results found'
else:
    json_object_results_by_year=[x for x in json_object['results'] if 'year' in x]
    json_sorted_results = sorted(json_object_results_by_year,key=lambda x:x['year'])
    #print json_sorted_results

Tags: 数据comapijsonhttpurlobjectdiscogs
1条回答
网友
1楼 · 发布于 2024-05-18 06:34:32
wanted = {u'CD',u'Album',u'Maxi-Single'}
[i for i in json_object[u'results'] if any(w in wanted for w in i[u'format'])]

或者

[i for i in json_object[u'results'] if any(w in i[u'format'] for w in wanted)]

相关问题 更多 >