Skip to content

Instantly share code, notes, and snippets.

@craigsapp
Created June 21, 2025 22:46
Show Gist options
  • Save craigsapp/ad8b2055461a34c584b31676316ac2a2 to your computer and use it in GitHub Desktop.
Save craigsapp/ad8b2055461a34c584b31676316ac2a2 to your computer and use it in GitHub Desktop.
Google Apps Script for accessing Polyrhythm Project metadata
// Google Apps Script for accessing metadata for the PolyRhythm project in JSON format
// URL: https://script.google.com/macros/s/AKfycbzcGajdIOFmC0ZpVXNgSfNdPFubSAYeo-_ltUmNV3_R0d4Siy1Dofc8e7XWbfd8Ax9MNg/exec
//////////////////////////////
//
// doGet -- Returns a GET request for the web app URL.
//
function doGet(event) {
let sid = "17rjKQ3lXJHEHAcDfOXTDNX5a0A_jVqwokcaqhd3Ddng";
let gid = "900860769";
let url = "https://docs.google.com/spreadsheets/d/"+sid+"/export?gid="+gid+"&format=tsv";
let appdata = UrlFetchApp.fetch(url);
let headerIndex = 0; // Line index of column headers.
let headerString = "HEADING"; // Regex of heading line (allows for comments above header line).
let suppressEmpty = true; // Save or throw away empty parameters for a line.
let obj = spreadsheetToObject(appdata.getContentText(), headerIndex, headerString, suppressEmpty);
let json = JSON.stringify(obj, null, "\t");
return ContentService.createTextOutput(json).setMimeType(ContentService.MimeType.JSON);
}
//////////////////////////////
//
// spreadsheetToObject -- Convert TSV form of spreadsheet into Javascript object.
//
function spreadsheetToObject(text, headerIndex, headerField, suppressEmpty) {
suppressEmpty = !!suppressEmpty;
let lines = text.match(/[^\r\n]+/g);
if (headerField) {
let testIndex = getHeaderIndex(lines, headerField);
if (testIndex >= 0) {
headerIndex = testIndex;
}
}
headerIndex = headerIndex < 0 ? 0 : headerIndex;
if (headerIndex >= lines.length) {
headerIndex = lines.length - 1;
}
let mapping = {};
let data = lines[headerIndex].split(/\t/);
for (let i=0; i<data.length; i++) {
if (data[i].match(/^\s*$/)) {
continue;
}
mapping[i] = data[i].trim();
}
var output = [];
for (let i=headerIndex+1; i<lines.length; i++) {
if (lines[i].match(/^\s*$/)) {
continue;
}
data = lines[i].split(/\t/);
var item = {};
for (let j=0; j<data.length; j++) {
if (suppressEmpty && data[j].match(/^\s*$/)) {
continue;
}
if (!mapping[j] || mapping[j].match(/^\s*$/)) {
continue;
}
item[mapping[j]] = data[j].trim();
}
output.push(item);
}
return output;
}
//////////////////////////////
//
// getHeaderIndex -- Given a target column header text, return the first
// line that has that text in a TSV line.
//
function getHeaderIndex(lines, targetField) {
for (let i=0; i<lines.length; i++) {
let data = lines[i].split(/\t/);
for (let j=0; j<data.length; j++) {
let value = data[j].trim();
if (value === targetField) {
return i;
}
}
}
return -1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment