Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

POSTed JSON to Google Apps Script, need to extract value and place in Google Sheets

I am posting a JSON to Google Apps Script and want to display a specific value from that JSON in Google Sheets.

I use the following code to get the data into my sheet from this post

function doPost(e) {
    Logger.log("I was called")
    if (typeof e !== 'undefined')
        Logger.log(e.parameter);
    var ss = SpreadsheetApp.openById("ID here")
    var sheet = ss.getSheetByName("Sheet1")
    sheet.getRange(1, 1).setValue(JSON.stringify(e))
    return ContentService.createTextOutput(JSON.stringify(e))
}

My sheet now displays:

{
   "parameter":{

   },
   "contextPath":"",
   "contentLength":20,
   "queryString":"",
   "parameters":{

   },
   "postData":{
      "type":"application/json",
      "length":20,
      "contents":"{\"myValue\":13}",
      "name":"postData"
   }
}

I only want it to display the value for myValue - which is the number 13 in this example.

I've tried a number of things suggested on these forums, I figured I was getting there with the solution from this post, and changed the code to:

function doPost(e) {
    Logger.log("I was called")
    if (typeof e !== 'undefined')
        Logger.log(e.parameter);
    var jsonString = e.postData.getDataAsString(); //added line
    var jsonData = JSON.parse(jsonString); // added line
    var ss = SpreadsheetApp.openById("ID here")
    var sheet = ss.getSheetByName("Sheet1")
    sheet.getRange(1, 1).setValue(JSON.stringify(jsonData.myValue)) //changed "e" to jsonData.myValue
    return ContentService.createTextOutput(JSON.stringify(jsonData.myValue)) //changed "e" to jsonData.myValue
}

This didn't work.

As a simple marketer, I wrestled with this for 2 nights now and feel I am pretty much stuck. So any help would be kindly appreciated. Cheers!

like image 971
MRI80 Avatar asked Jan 20 '26 04:01

MRI80


1 Answers

You can do something like the following:

function doPost(request) {
  var ss = SpreadsheetApp.openById("ID here")
  var sheet = ss.getSheetByName("Sheet1")
  // Now Parse the body of your post request in to a data object

  var data = JSON.parse (request.postData.contents)
  //Now put the data in the sheet
  sheet.getRange(1, 1).setValue(data['myValue'])
  // Note no need to stringify 
  // now do your other stuff

The body of the post request is available to you in request .postData.contents. Here's the Google documentation

You parse the content string into a JSON object and then access the fields you need.

like image 124
abir Avatar answered Jan 21 '26 20:01

abir



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!