我使用Discogs API获取数据,我想将JSON限制为只有格式为'CD'或'Album'或'Maxi-Single'的记录。我不确定如何过滤提取的数据,因为Discogs没有更简单的方法从初始请求本身过滤它。你会注意到下面提到的JSON URL有'DVD'和'VHS',我想省略。任何想法/线索如何在完成提取后过滤这个?
的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
答案 0 :(得分:3)
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)]