首页 > 解决方案 > 如何使用 Google Apps 脚本将 JSON 文件保存到 Google Drive?

问题描述

我有一个需要来自 JSON 文件的训练数据的神经网络脚本,是否可以使用 Google Apps 脚本将 JSON 文件保存到 Google Drive?

标签: jsonfilegoogle-apps-script

解决方案


您可以使用高级驱动器服务。在 Google Drive 中创建文件有 3 个选项。

  • DriveApp - 内置应用程序脚本服务
  • 高级驱动服务 - 特定于 Apps 脚本 - 必须添加。
  • Drive API - 必须使用 REST API 选项

目前,Apps Script 既有旧版代码编辑器,也有新版代码编辑器。在两个编辑器中启用高级驱动器服务是不同的。

旧版编辑器:

  • “资源”菜单
  • “高级谷歌服务”
  • 在列表中找到“Drive API”
  • 单击按钮将其打开

新编辑器:

  • 点击左侧边栏中的“服务”
  • 在列表中找到“Drive API”,点击它
  • 点击“添加”按钮

过去,您还需要在 Google Cloud Platform 中启用 Drive API。但现在你有两个选择。

  • 使用“默认”Google Cloud 项目 - 您无需在 Google Cloud Platform 中显式启用 Drive API。
  • 创建一个新的“标准”Google Cloud 项目并将其与您的 Apps 脚本项目相关联。您需要在 Google Cloud Platform 中启用 Drive API。

如果 Apps Script 项目将被公众使用,那么您应该创建一个“标准”Google Cloud 项目,并在 Google Cloud Platform 中启用 Google Drive API。

代码:

function saveAsJSON() {
  var blob,file,fileSets,obj;
  
  obj = {//Object literal for testing purposes
    key:"value"
  }

/**
 * Creates a file in the users Google Drive
 */
  
  fileSets = {
    title: 'AAA_Test.json',
    mimeType: 'application/json'
  };
  
  blob = Utilities.newBlob(JSON.stringify(obj), "application/vnd.google-apps.script+json");
  file = Drive.Files.insert(fileSets, blob);
  Logger.log('ID: %s, File size (bytes): %s, type: %s', file.id, file.fileSize, file.mimeType);

}

推荐阅读