为了账号安全,请及时绑定邮箱和手机立即绑定

解析来自 Google Sheet Web App 的字符串化 JSON

解析来自 Google Sheet Web App 的字符串化 JSON

慕桂英546537 2023-04-20 10:18:03
我正在尝试解析从 google 表格脚本创建的网络应用程序的字符串化 JSON 输出。我认为它不会那么复杂,但我已经尝试了我能想到的或在网上找到的所有东西......所以如果可以的话现在寻求帮助!在网络应用程序/谷歌表格方面,代码是:function doGet(e) {    var spreadsheet = SpreadsheetApp.openById('spreadsheetID');  var worksheet = spreadsheet.getSheetByName('Rankings C/U');  var output = JSON.stringify({ data: worksheet.getDataRange().getValues() });    return HtmlService.createHtmlOutput(output);}我已经发布了脚本,Web 应用程序可以运行,我对此很满意。我在电子表格中放置了随机值:[[1,2],[3,4]] 如果我们以矩阵格式说话。另一方面,我尝试了很多东西,包括 .fetch、JSON.parse() 以在 Google 站点嵌入式代码中以可用格式获取数据,但真正的问题是我认为我无法获取将有效负载分配给变量?我正在使用 Google 协作平台来获取数据。使用基本模块“<> embed”,使用“by URL”选项,使用以下代码:https://script.google.com/macros/s/scriptID/exec我得到以下输出 - 看起来应该是这样的:{"data":[[1,2],[3,4]]}但是当试图将其包含在脚本模块(“嵌入代码”)中时 - 没有机会!<form name="get-images">  <input name="test" id="test" value="we'll put the contents of cell A1 here"></form><script>   const form = document.forms['get-images']   var usableVariable = JSON.parse("https://script.google.com/macros/s/scriptID/exec"); // here I'm trying to allocate the stringified JSON to a variable   form.elements['test'].value = usableVariable[1,1]; //allocating the first element of the parsed array  </script>我很确定我错过了一些明显的东西 - 但现在我没有想法了!谢谢你的帮助 :)
查看完整描述

1 回答

?
胡子哥哥

TA贡献1825条经验 获得超6个赞

我相信你的目标如下。

  • 在您的情况下,底部脚本嵌入到 Google 站点。

  • 您想要从中检索值doGet并将单元格“B2”的值放入输入标签。

  • Web Apps 的设置是Execute the app as: MeWho has access to the app: Anyone, even Anonymous

修改点:

  • 对于您的情况,我认为这return ContentService.createTextOutput(output);return HtmlService.createHtmlOutput(output);在 Google Apps 脚本中更合适。

  • 为了从中检索值doGet,在此修改中,fetch使用了。

  • 您要从 中检索单元格“B2” usableVariable[1,1];,请将其修改为usableVariable[1][1];

当以上几点反映到您的脚本中时,它会变成如下。

修改脚本:

Google Apps 脚本端:

function doGet(e) {

  var spreadsheet = SpreadsheetApp.openById('spreadsheetID');

  var worksheet = spreadsheet.getSheetByName('Rankings C/U');

  var output = JSON.stringify({ data: worksheet.getDataRange().getValues() });

  return ContentService.createTextOutput(output);

}

HTML 和 Javascript 端:

<form name="get-images">

  <input name="test" id="test" value="we'll put the contents of cell A1 here">

</form>


<script>

  let url = "https://script.google.com/macros/s/###/exec";

  fetch(url)

    .then((res) => res.json())

    .then((res) => {

      const usableVariable = res.data;

      const form = document.forms['get-images'];

      form.elements['test'].value = usableVariable[1][1];  // usableVariable[1][1] is the cell "B2".

    });

</script>

笔记:

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

  • 在我的环境中,我可以通过嵌入确认上述 HTML 和 Javascript 在 Google 站点中有效。


查看完整回答
反对 回复 2023-04-20
  • 1 回答
  • 0 关注
  • 89 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信