google-apps-scriptspotify

Handling a href in an API Script


I am using Google Apps Script to pull from the Spotify API. I am able to extract almost everything, but I get struck when there's an href..

My code below will extract the playlist name but not the artist name after the href... ideas?

MY code -

function artistName(playlist_id) {
  //searches spotify and returns artist ID
  var response = UrlFetchApp.fetch("https://api.spotify.com/v1/playlists/" + playlist_id + "/tracks", 
  { method: "GET",
    headers:{
      "contentType": "application/json",
      'Authorization': "Bearer REMOVED FOR SECURITY"
            },
  });
  json = response.getContentText();
  var data = JSON.parse(json);
  var listName = [];
  for(var i = 0, len = data.items.length; i < len; i++){
    listName.push(data.items[i].track.album.name); //will return the album name, but I want it to return the artist name after href
                 }
  return listName;
}

Solution

  • Basically, the issue is how you're accessing the object values.

    The correct order would be data.items[i].track.album.artists[0].name

    The complete script with modification would look like this:

    function artistName(playlist_id) {
      //searches spotify and returns artist ID
      var response = UrlFetchApp.fetch("https://api.spotify.com/v1/playlists/" + playlist_id + "/tracks", 
      { method: "GET",
        headers:{
          "contentType": "application/json",
          'Authorization': "Bearer REMOVE FOR SECURITY"
        },
      });
      json = response.getContentText();
      var data = JSON.parse(json);
      var listName = [];
      for(var i = 0, len = data.items.length; i < len; i++){
        listName.push(data.items[i].track.album.artists[0].name);//this will return the artist name after href
      }
    
      /* For multiple artists
      for(var i = 0, len = data.items.length; i < len; i++){
        var artists = data.items[i].track.album.artists;
        artists.forEach((artist) => {
          listName.push(artist.name);
        });
      }
      */
      return listName;
    }