doPost() from Google Apps Script - Passing Sheet Data into JSON

I have CSVโ€™s sent to me on a daily basis which need to be added to a table in my app. Iโ€™m having them automatically sent to a folder on my drive which will trigger a doPost script Iโ€™m working on. I have the spreadsheet importing and converting to JSON, however, I canโ€™t figure out how to pass all of the rows of my spreadsheet into the POST request.

function doPost() {
var apiurl = โ€˜https://api.appsheet.com/api/v2/apps/MYAPPID/tables/MYTABLE/Actionโ€™;

var result = {};
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(โ€˜THE SHEET I WANT TO IMPORTโ€™)
.getDataRange()
.getValues();

result.sheet = makeObject(sheet);

Logger.log(result.sheet);

var body = {
โ€œActionโ€: โ€œAddโ€,
โ€œPropertiesโ€: {
โ€œLocaleโ€: โ€œen-USโ€,
โ€œLocationโ€: โ€œ47.623098, -122.330184โ€,
โ€œTimezoneโ€: โ€œEastern Standard Timeโ€,
โ€œRunAsUserEmailโ€: โ€œmyemail@ICANTCODEFORSHIT.comโ€
},
โ€œRowsโ€: [{
โ€œMY COLUMN NAME 1โ€: HOW DO I REFERENCE COLUMN 1 OF MY SHEET?,
โ€œMY COLUMN NAME 2โ€: WTF DO I PUT HERE? WHY CAN I NOT FIGURE THIS OUT?

  }

]
}}
var options = {
โ€˜headersโ€™ : {โ€˜ApplicationAccessKeyโ€™ : โ€˜MYAPPLICATIONACCESSKEYโ€™,
โ€˜Acceptโ€™ : โ€˜application/json, application/geo+json, application/gpx+xml, img/png; charset=utf-8โ€™,
โ€˜Authorizationโ€™: โ€˜โ€™
},

	'method' : 'POST',
	'muteHttpExceptions': true,
	'contentType': 'application/json',
  'payload': JSON.stringify(body),
	
};

console.log(JSON.stringify(options));
var response = UrlFetchApp.fetch(apiurl, options);

}

1 5 6,328
5 REPLIES 5

You didnโ€™t provide the makeObject() code but thatโ€™s where you would return the JSON that would go into the Rows.
See https://stackoverflow.com/questions/47555347/creating-a-json-object-from-google-sheets

Thanks for the tip! How do I format the โ€œRowsโ€ section?
Thatโ€™s what I canโ€™t figure out. Would it be something like this?

โ€œColumn 1โ€: object[0],
โ€œColumn 2โ€:object[1]

...
โ€œRowsโ€: [getJsonFromSheet(sheet)],
...

where

function getJsonFromSheet(data)
{

  var obj = {};
  var result = [];
  var headers = data[0];
  var cols = headers.length;
  var row = [];

  for (var i = 1, l = data.length; i < l; i++)
  {
    // get a row to fill the object
    row = data[i];
    // clear object
    obj = {};
    for (var col = 0; col < cols; col++) 
    {
      // fill object with new values
      obj[headers[col]] = row[col];    
    }
    // add object in a final result
    result.push(obj);  
  }

  return result;  

}

omg, that took so long for me to figure out how to plug everything together but it finally works. Thank you so much!!!

Youโ€™re welcome.

Top Labels in this Space