javascript - 将 JSON 发布到 Google Apps 脚本,需要提取值并放置在 Google 表格中

标签 javascript google-apps-script

我正在将 JSON 发布到 Google Apps 脚本,并希望在 Google 表格中显示来自该 JSON 的特定值。

我使用以下代码将数据放入我的工作表中 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))
}

我的工作表现在显示:

{
   "parameter":{

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

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

我只希望它显示 myValue 的值 - 在本例中为数字 13。

我已经尝试了这些论坛上建议的许多事情,我想我是通过 this post 中的解决方案到达那里的,并将代码更改为:

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
}

这没有用。

作为一名简单的营销人员,我为此苦苦挣扎了 2 个晚上,感觉自己几乎被困住了。因此,我们将不胜感激任何帮助。干杯!

最佳答案

您可以执行以下操作:

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

您可以在 request.postData.contents 中找到发布请求的正文。 Here's the Google documentation

您将内容字符串解析为 JSON 对象,然后访问您需要的字段。

关于javascript - 将 JSON 发布到 Google Apps 脚本,需要提取值并放置在 Google 表格中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48903932/

相关文章:

javascript - 如果没有 map.fitBounds,谷歌地图显示灰色

javascript - 如果 value 为 null,如何正确跳过 setValue

google-apps-script - 将 Google 表单响应映射或导出到 PDF 表单字段

javascript - 如何使用脚本同步谷歌日历和电子表格

javascript - 为什么在 ES6 中不使用绑定(bind)到它的类创建的对象的方法?

javascript - 使用 Dygraph 很难指向非常接近的时间序列点

google-apps-script - 将图标添加到部署为 Web 应用程序 ("Add to home screen"的应用程序脚本)

javascript - 如何将数组写入 Google 电子表格?

javascript - 如何将javascript日期转换为特定时区

javascript - 从对象数组中获取特定数据并转换为对象