前回↓につづきスプレッドシートの処理。
uyamazak.hatenablog.com
前回は1つのJSONだからメッセージに出してコピペで良かった。
でも今回は都道府県ごとに数百文字のテキストがあり、すべてを1ファイルにまとめてしまうと100KB近くいってしまい、Ajaxでの取得に時間がかかりそうなので、都道府県ごとにファイル分割することにしました。
最初はすべてをまとめたJSONを書き出して、ローカルPCでファイルごとに分割する処理をシェルスクリプトかなにかでやろうかと思いましたが、よく考えるとそれ、Googleドライブでできるのでは?と思い調べてみたら簡単そうなのでやりました。
ファイルの書き出し、文字コードの指定はこちらを参考にしました。
hrroct.hatenablog.com
スプレッドシート側のデータ構造はこんな感じ(まだテキストは入ってない)
これを1行ずつ都道府県コードをファイル名としてファイル保存にします。
コードはこんな感じ。
function createJsonFiles() {
const sheet = SpreadsheetApp.getActiveSheet();
const rows = sheet.getSheetValues(1, 1, sheet.getLastRow(), sheet.getLastColumn());
const parentFolder = DriveApp.getFolderById('{フォルダのID}');
const folderName = Utilities.formatDate(new Date(), 'Asia/Tokyo', 'yyyy-MM-dd_HH-mm-ss');
const folder = DriveApp.createFolder(folderName).moveTo(parentFolder)
const contentType = 'text/json';
const charset = 'utf-8';
rows.forEach(function(cols, index) {
if (index === 0) {
return
}
const prefCode = cols[0]
const prefName = cols[1]
const textAll = cols[2]
const text50 = cols[3]
const text60 = cols[4]
const text70 = cols[5]
const fileName = `${prefCode}.json`
const content = {
'name': prefName,
'textAll': textAll,
'text50': text50,
'text60': text60,
'text70': text70,
}
const blob = Utilities.newBlob('', contentType, fileName)
.setDataFromString(JSON.stringify(content), charset);
folder.createFile(blob);
})
}
最初、一つのフォルダに書き出せば、再度実行した際に上書きされるかと思いましたが、Googleドライブは実際にはIDで管理しているので、実行するたびに同名のファイルができてしまいました。
そのため、指定のフォルダの下に実行日時を元にフォルダを作り、そこに入れることにしました
const parentFolder = DriveApp.getFolderById('{フォルダのID}');
const folderName = Utilities.formatDate(new Date(), 'Asia/Tokyo', 'yyyy-MM-dd_HH-mm-ss');
const folder = DriveApp.createFolder(folderName).moveTo(parentFolder)
DriveApp.createFolder(ファイル名)だけでは、他のフォルダに配置することができないので、作成した後に、moveTo(親フォルダ)が必要でした。
developers.google.com
実行すると日時のフォルダができて、こんな感じで出力されました。
更新頻度によってはCMS使ったり、専用アプリ作った方がいいけど、こんな雑なGASとG Suiteで十分な場面は結構あるなぁと思いました。