【发布时间】:2020-07-05 18:50:31
【问题描述】:
我正在尝试在 Google-Apps-Script(Webhook 接收器)中处理简单的 JSON 数据。对于测试,我从控制台发送数据:
curl -d "{"result":true,"count":42,"exchange":"Kroakex"}" -H "Content-Type: application/json" -X POST https://script.google.com/macros/s/xxx/exec
...但我无法访问处理函数中的 json 元素:
function doPost(e) {
var jsonString = JSON.stringify(e.postData.contents);
var jsonObj = JSON.parse(jsonString);
console.log(jsonObj); // ---> "{result:true,count:42,exchange:Kroakex}"
console.log(jsonObj.count); // ---> "undefined"
var sheet = SpreadsheetApp.getActiveSheet();
var lastRow = Math.max(sheet.getLastRow(),1);
sheet.insertRowAfter(lastRow);
sheet.getRange(lastRow + 1, 1).setValue(jsonObj['count']); // ---> nothing
sheet.getRange(lastRow + 1, 2).setValue(jsonObj['exchange']); // ---> nothing
sheet.getRange(lastRow + 1, 3).setValue(jsonObj); // ---> {result:true,count:42,exchange:Kroakex}
SpreadsheetApp.flush();
return HtmlService.createHtmlOutput("post request received");
}
当我改为使用这一行手动创建 JSON 字符串时,一切正常:
const jsonString = '{"result":true, "count":42, "exchange":"Kroakex"}';
谁能帮忙?
【问题讨论】:
-
根据Documentation e.postData.contents 已经是文本,为什么要在上面使用stringify?
-
谢谢你,你可能是对的......但是当我离开该行时,我在以下解析行收到错误“位置 0 处的意外标记”
标签: json parsing google-apps-script split webhooks