Home > Blockchain >  FetchingURL Using JSON on Google Sheets v2
FetchingURL Using JSON on Google Sheets v2

Time:09-02

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

It seems that the specification has changed again. And I'm not sure how to fix it. Any guidance or help would be greatly appreciated!

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

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(/"followers":({[\s\S\w] ?})/);
  return v && v.length == 2 ? JSON.parse(v[1].trim()).total : "Value cannot be 
retrieved.";
}

Thanks!

CodePudding user response:

In the current stage, it seems that the JSON data is put as base64 data, and also, the structure of the object was changed. So, as the current sample script, how about the following sample script?

Sample script:

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.";
}

Note:

  • This sample script is for the current HTML data. So, I think that this might be changed in the future update. So, I also would like to recommend using the API for your future work as it has already been mentioned in the comment.
  • Related