在 Google AppScript 中从本地加载或读取 JSON

g0c*_*33k 4 google-apps-script google-forms

我正在寻找一个 json 文件,即config.json从 AppScript 中读取config.json. 我不知道如何阅读 JSON 文件 - 有人可以帮我吗?一些示例代码将不胜感激..谢谢

Par*_*tik 11

如果您像我一样,您可能已经在此处查看了如何将 JSON 文件存储在实际的 Apps 脚本项目中(例如与 Code.gs 一起),然后在 Code.gs 中检索它。

我这样做了:

  • 将 HTML 文件添加到您的项目中。
  • 删除HTML 文件的所有内容并放入 JSON
  • 在您的 Code.gs 文件中,使用类似以下内容的内容:
//Assume the file you added to your project is called 'my-json.html'

const jsonString = HtmlService.createHtmlOutputFromFile("my-json.html").getContent();
const jsonObject = JSON.parse(jsonString);
Run Code Online (Sandbox Code Playgroud)


Ami*_*wal 6

假设您的文件在 Google Drive 中,您可以使用 DriveApp 服务读取文件并解析它。

function getFileContent() {
  var fileName = "config.json.txt";
  var files = DriveApp.getFilesByName(fileName);
  if (files.hasNext()) {
    var file = files.next();
    var content = file.getBlob().getDataAsString();
    var json = JSON.parse(content);
    Logger.log(json);
  }
}
Run Code Online (Sandbox Code Playgroud)

确保 Google Drive 没有将文本文件转换为原生格式,否则脚本将无法解析它。