猿问

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

我正在尝试解析从 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>

我很确定我错过了一些明显的东西 - 但现在我没有想法了!


谢谢你的帮助 :)


慕桂英546537
浏览 90回答 1
1回答

胡子哥哥

我相信你的目标如下。在您的情况下,底部脚本嵌入到 Google 站点。您想要从中检索值doGet并将单元格“B2”的值放入输入标签。Web Apps 的设置是Execute the app as: Me和Who has access to the app: Anyone, even Anonymous。修改点:对于您的情况,我认为这return ContentService.createTextOutput(output);比return HtmlService.createHtmlOutput(output);在 Google Apps 脚本中更合适。为了从中检索值doGet,在此修改中,fetch使用了。您要从 中检索单元格“B2”&nbsp;usableVariable[1,1];,请将其修改为usableVariable[1][1];当以上几点反映到您的脚本中时,它会变成如下。修改脚本:Google Apps 脚本端:function doGet(e) {&nbsp; var spreadsheet = SpreadsheetApp.openById('spreadsheetID');&nbsp; var worksheet = spreadsheet.getSheetByName('Rankings C/U');&nbsp; var output = JSON.stringify({ data: worksheet.getDataRange().getValues() });&nbsp; return ContentService.createTextOutput(output);}HTML 和 Javascript 端:<form name="get-images">&nbsp; <input name="test" id="test" value="we'll put the contents of cell A1 here"></form><script>&nbsp; let url = "https://script.google.com/macros/s/###/exec";&nbsp; fetch(url)&nbsp; &nbsp; .then((res) => res.json())&nbsp; &nbsp; .then((res) => {&nbsp; &nbsp; &nbsp; const usableVariable = res.data;&nbsp; &nbsp; &nbsp; const form = document.forms['get-images'];&nbsp; &nbsp; &nbsp; form.elements['test'].value = usableVariable[1][1];&nbsp; // usableVariable[1][1] is the cell "B2".&nbsp; &nbsp; });</script>笔记:当您修改 Web Apps 的 Google Apps Script 时,请将 Web Apps 重新部署为新版本。由此,最新的脚本被反映到Web Apps。请注意这一点。在我的环境中,我可以通过嵌入确认上述 HTML 和 Javascript 在 Google 站点中有效。
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答