gpt4 book ai didi

Python JSON如何过滤返回的数据

转载 作者:行者123 更新时间:2023-11-30 23:38:25 31 4
gpt4 key购买 nike

我正在使用 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

最佳答案

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

关于Python JSON如何过滤返回的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14547918/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com