在Google Apps Script中处理Spotify API的href提取艺术家名称
解决Google Apps Script调用Spotify API获取艺术家名称的问题
你的问题核心是没搞清楚Spotify API返回的歌曲数据结构:艺术家信息并不需要通过href去额外请求,而是直接包含在track.artists数组中——href只是该艺术家资源的API链接,实际名称就在同层级的name字段里。
修改后的代码
function getArtistNames(playlist_id) { var response = UrlFetchApp.fetch("https://api.spotify.com/v1/playlists/" + playlist_id + "/tracks", { method: "GET", headers:{ "Authorization": "Bearer REMOVED FOR SECURITY" }, }); var json = response.getContentText(); var data = JSON.parse(json); var artistNames = []; for(var i = 0, len = data.items.length; i < len; i++){ // 单首歌可能有多个艺术家,这里取第一个,若要全部可遍历数组拼接 var firstArtist = data.items[i].track.artists[0]; artistNames.push(firstArtist.name); // 如果需要同时获取艺术家的href,可改成: // artistNames.push({name: firstArtist.name, href: firstArtist.href}); } return artistNames; }
关键说明
- 数据结构解析:Spotify API返回的
track对象中,artists是一个数组,每个元素是包含name、href、id等字段的艺术家对象。 - 多艺术家处理:如果歌曲有多个合作艺术家,你可以遍历
artists数组,把所有艺术家名称拼接成字符串(比如用data.items[i].track.artists.map(artist => artist.name).join(", "))。 - 冗余参数移除:原请求中的
contentType是多余的,GET请求不需要设置这个头,已移除。
内容的提问来源于stack exchange,提问作者devR
相关产品推荐
相关产品推荐

