我正在使用Spotify Web API的this端点。我使用fields
查询参数来单独请求我需要的数据。
没有任何过滤,从API返回的JSON将包含一个名为items
的数组。 items
的每个对象中的第一个键称为added_at
。要接收此密钥,只需要字段参数为items(added_at)
。
items
的每个对象中都有一个名为track
的密钥。在track
内,有一个名为artists
的数组。 artists
的每个条目都有一个名为name
的密钥。所以这应该与第二段中描述的情况相同。因此,我只能使用items(track(artists(name)))
来获取艺术家的名字。
实际上这确实会返回整个artists
数组。似乎忽略了(name)
选择器。
items(added_at, track(artists))
&的回复items(added_at, track(artists(name)))
实际上是相同的,看起来像这样:
{
"items": [
{
"added_at": "2017-08-24T14:56:20Z",
"track": {
"artists": [
{
"external_urls": {
"spotify": "https://open.spotify.com/artist/4V8Sr092TqfHkfAA5fXXqG"
},
"href": "https://api.spotify.com/v1/artists/4V8Sr092TqfHkfAA5fXXqG",
"id": "4V8Sr092TqfHkfAA5fXXqG",
"name": "Luis Fonsi",
"type": "artist",
"uri": "spotify:artist:4V8Sr092TqfHkfAA5fXXqG"
},
{
"external_urls": {
"spotify": "https://open.spotify.com/artist/4VMYDCV2IEDYJArk749S6m"
},
"href": "https://api.spotify.com/v1/artists/4VMYDCV2IEDYJArk749S6m",
"id": "4VMYDCV2IEDYJArk749S6m",
"name": "Daddy Yankee",
"type": "artist",
"uri": "spotify:artist:4VMYDCV2IEDYJArk749S6m"
}
]
}
}
]
}
那么我怎样才能过滤艺术家数组,只使用查询参数来显示艺术家的名字?我错误地认为items
& added_at
可与artists
& name
因此我使用的语法是错误的还是我还缺少其他东西?
items(track.artists(name))
& items(track.artists)
。答案 0 :(得分:0)
通过文档网页尝试端点,你不会走得太远。以编程方式尝试。
下面我将展示如何使用直接请求(python请求)和api(playlists
)的一个很好的包装来访问spotipy
端点。
将链接的spotify网页上生成的访问令牌复制到与此脚本相同的路径中的文件中,例如playlists.py
。
您可以从所查询的所有播放列表中获取艺术家的姓名:
import requests
import spotipy
import spotipy.util as util
import json
SEARCH_PLAYLIST_ENDPOINT ='https://api.spotify.com/v1/search?type=playlist'
def search_playlist(name):
path = 'token.json'
with open(path) as t:
token = json.load(t)
myparams = {'type': 'playlilst'}
myparams['q'] = name
resp = requests.get(SEARCH_PLAYLIST_ENDPOINT, params=myparams, headers={"Authorization": "Bearer {}".format(token)})
pprint (resp.json())
return resp.json()
def query_playlist(playlist):
path = 'token.json'
with open(path) as t:
token = json.load(t)
sp = spotipy.Spotify(auth=token)
data = search_playlist(playlist)
# get playlists
playlists = data['playlists']['items']
for playlist in playlists:
uri = playlist['uri']
username = uri.split(':')[2]
playlist_id = uri.split(':')[4]
# query playlists
results = sp.user_playlist(username, playlist_id)
# separate data by track
tracks = results['tracks']
# lookup
for item in tracks['items']:
track = item['track']
artist = track['artists'][0]['name']
print artist
print query_playlist('rock and roll')