【发布时间】:2020-07-11 10:03:35
【问题描述】:
我使用 Spotify API 收到 JSON 响应,我正在尝试访问名为“name”的元素(一个说“3 Doors Down”,另一个以“Bret Michaels”开头)似乎在“项目的元素,但我似乎无法找到解决方案。
这是我加载数据的方式:
search_results = requests.get(search_url + 'q=' + query + '&type=artist', headers=granted_headers).json()
这是我的 JSON 数据:
{
'artists': {
'href': 'https://api.spotify.com/v1/search?query=3+doors+down&type=artist&offset=0&limit=20',
'items': [
{
'external_urls': {
'spotify': 'https://open.spotify.com/artist/2RTUTCvo6onsAnheUk3aL9'
},
'followers': {
'href': None,
'total': 2631330
},
'genres': [
'alternative metal',
'nu metal',
'pop rock',
'post-grunge'
],
'href': 'https://api.spotify.com/v1/artists/2RTUTCvo6onsAnheUk3aL9',
'id': '2RTUTCvo6onsAnheUk3aL9',
'images': [
{
'height': 640,
'url': 'https://i.scdn.co/image/ead4e883a59d30d8c157385aa531d3fe8e688fc0',
'width': 640
},
{
'height': 320,
'url': 'https://i.scdn.co/image/611a4fd8aaf2637c5894acf65f12e79d75926329',
'width': 320
},
{
'height': 160,
'url': 'https://i.scdn.co/image/f1a1a2c37f2f6d242b1ab7ae3f4d893bf5822095',
'width': 160
}
],
'name': '3 Doors Down',
'popularity': 72,
'type': 'artist',
'uri': 'spotify:artist:2RTUTCvo6onsAnheUk3aL9'
},
{
'external_urls': {
'spotify': 'https://open.spotify.com/artist/2kPbQDZvnasPcCuXbq6YQx'
},
'followers': {
'href': None,
'total': 156
},
'genres': [
],
'href': 'https://api.spotify.com/v1/artists/2kPbQDZvnasPcCuXbq6YQx',
'id': '2kPbQDZvnasPcCuXbq6YQx',
'images': [
],
'name': 'Bret Michaels (Featuring Brad Arnold of 3 Doors Down, Chris Cagle, Mark Wills)',
'popularity': 4,
'type': 'artist',
'uri': 'spotify:artist:2kPbQDZvnasPcCuXbq6YQx'
}
],
'limit': 20,
'next': None,
'offset': 0,
'previous': None,
'total': 4
}
}
【问题讨论】:
-
添加了答案。如果你告诉我你到底想用这些名字做什么,我可以相应地更新我的答案。
-
我正在使用 Django 通过上下文字典将它们传递给模板,但我已经知道该怎么做。运行您的代码时,我仍然收到 KeyError。
-
你能贴出实际的错误吗?
标签: json django dictionary python-requests element