我正在将 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/