Python JSON如何过滤返回的数据

时间:2013-01-27 13:36:07

标签: python json discogs-api

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

JSON网址: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

1 个答案:

答案 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)]