亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

解析來自 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 關注
  • 113 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號