0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

[AI生成]GASスプレッドシートからJSONファイル文字列を作成するGASプログラム

0
Posted at

AIに質問してGASスプレッドシートからJSONファイル文字列を作成するGASプログラムを作ってもらいました。


GASプログラム内容

// 1行目に見出し、次の行で値の順序
function convertSheetToJson() {
const sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
const rows = sheet.getDataRange().getDisplayValues();
if (rows.length < 2) {
Logger.log("データがありません");
return;
}
const headers = rows[0]; // 1行目をキーにする
const dataRows = rows.slice(1); // 2行目以降を取得
const jsonArray = dataRows.map(row => {
let obj = {};
headers.forEach((header, index) => {
obj[header] = row[index];
});
return obj;
});
const jsonString = JSON.stringify(jsonArray, null, 2);
Logger.log(jsonString); // ログに出力
return jsonString;
}
//行列転置バージョン
//一列目に見出し、二列目で値の順序
function convertSheetToJsonTransposed() {
const sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
const rows = sheet.getDataRange().getDisplayValues();
if (rows.length === 0 || rows[0].length < 2) {
Logger.log("データがありません(少なくとも2列必要です)");
return;
}
// 1列目からヘッダー(キー名)を取得
const headers = rows.map(row => row[0]);
// 2列目以降の列数を計算
const colCount = rows[0].length;
const jsonArray = [];
// 2列目(インデックス1)から順に、列ごとのオブジェクトを作成
for (let c = 1; c < colCount; c++) {
let obj = {};
headers.forEach((header, r) => {
// 空白のヘッダーはスキップ、または必要に応じて処理
if (header !== "") {
obj[header] = rows[r][c];
}
});
jsonArray.push(obj);
}
const jsonString = JSON.stringify(jsonArray, null, 2);
Logger.log(jsonString); // ログに出力
return jsonString;
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?