Home > Software engineering >  FetchingURL Using JSON on Google Sheets v3
FetchingURL Using JSON on Google Sheets v3

Time:12-22

I have a code in JSON in Google Apps Scripts that takes a Spotify URL and pastes the amount of followers in the cell where you reference the url, for example =SAMPLE(A2) (where A2 holds the URL)

The value being returned is blank, and no error message is prompted. I have tried using a Spotify API, but this is impossible when taking data from a Spotify account that you don't own (from my understanding at least).

Here's the original post = FetchingURL Using JSON on Google Sheets v2

Here's the code I have currently in Google Apps Scripts. (courtesy of @Tanaike)

function SAMPLE(url) {
  const res = UrlFetchApp.fetch(url).getContentText();
  const v = res.match(/<script id\="initial-state" type\="text\/plain">([\s\S\w] ?)<\//);
  if (!v || v.length != 2) return "Value cannot be retrieved.";
  const obj = JSON.parse(Utilities.newBlob(Utilities.base64Decode(v[1].trim())).getDataAsString());
  const value = Object.entries(obj.entities.items).reduce((n, [k, o]) => {
    if (k.includes("spotify:playlist:")) n.push(o.followers.total);
    return n;
  }, []);
  return value.length > 0 ? value[0] : "Value cannot be retrieved.";
}

CodePudding user response:

In your showing script, how about the following modification?

From:

if (k.includes("spotify:playlist:")) n.push(o.followers.total);

To:

if (k.includes("spotify:playlist:")) n.push(o.followers);
  • It seems that the specification of the JSON object has been changed.
  • Related