Google 工作表 API 仅返回不必要的信息

Google Sheets API only returning unecessary information

目标如下:将 Google 表格数据用作 Dialogflow 作为 fulfillmentText。这是当前代码(使用 Google Apps 脚本):

function doPost(e) {
  // This code uses the Sheets Advanced Service, but for most use cases
  // the built-in method SpreadsheetApp.getActiveSpreadsheet()
  //     .getRange(range).getValues(values) is more appropriate.
  var ranges = ['Sheet1!B1'];
  var result = Sheets.Spreadsheets.Values.batchGet('sheetId, {ranges: ranges});
  Logger.log(JSON.parse(result));
  //Transforms the read value from Sheets into JSON format
  return ContentService.createTextOutput(JSON.stringify(result))
            .setMimeType(ContentService.MimeType.JSON);
} 

第一个问题是从电子表格中读取时,不是只获取请求的值,而是输出:

 {valueRanges=[{majorDimension=ROWS, values=[[Content here...]], range=Sheet1!B1}], spreadsheetId=XXXYYYZZZ}

与电子表格相关的信息不是必需的。只需要范围内容。到目前为止,还无法清除输出的 JSON 中的电子表格部分。我没有在文档中找到有关此问题的任何信息。

第二个问题是:return ContentService.createTextOutput(JSON.stringify(result)).setMimeType(ContentService.MimeType.JSON)中的内容转换为JSON后,之前的内容被包裹在values字段中:https://developers.google.com/apps-script/guides/content#serving_json_from_scripts

{
  "valueRanges": [
    {
      "range": "Sheet1!B1",
      "majorDimension": "ROWS",
      "values": [
        [
          "Note that we link to certain 3rd party products via affiliate or sponsored links"
        ]
      ]
    }
  ],
  "spreadsheetId": "XXXYYYZZZ"
}

总结一下,第一个问题是只读取表格 API 中的内容,而不是:sheetId、范围和 majorDimension...第二个是发送 JSON 值从 values 字段中展开。这是 Dialogflow 中符合条件的响应格式: https://cloud.google.com/dialogflow/docs/fulfillment-webhook#text_response

提前致谢!!!

我相信你的目标如下。

  • 您想从以下对象中检索 "Note that we link to certain 3rd party products via affiliate or sponsored links" 的内容。你想要 return 像 {"values": content}.

    这样的内容
    {
      "valueRanges": [
        {
          "range": "Sheet1!B1",
          "majorDimension": "ROWS",
          "values": [
            [
              "Note that we link to certain 3rd party products via affiliate or sponsored links"
            ]
          ]
        }
      ],
      "spreadsheetId": "XXXYYYZZZ"
    }
    

为此,这个答案怎么样?

修改点:

  • Sheets.Spreadsheets.Values.batchGet returns 已解析的 JSON 对象。所以不需要使用JSON.parse.
  • 为了从响应值中检索值,您可以使用 result.valueRanges[0].values。而且,当检索到第一个元素时,请使用 result.valueRanges[0].values[0][0].

修改后的脚本:

当您的脚本修改时,请修改如下。

从:
Logger.log(JSON.parse(result));
//Transforms the read value from Sheets into JSON format
return ContentService.createTextOutput(JSON.stringify(result))
          .setMimeType(ContentService.MimeType.JSON);
到:
var content = result.valueRanges[0].values[0][0];
var res = {values: content};
return ContentService.createTextOutput(JSON.stringify(res)).setMimeType(ContentService.MimeType.JSON);
  • 如果要检索 "values",请使用 result.valueRanges[0].values 而不是 result.valueRanges[0].values[0][0]

注:

  • 当您修改了Web Apps的脚本后,请将Web Apps重新部署为新版本。由此,最新的脚本被反​​映到Web Apps。请注意这一点。