0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Google Apps ScriptでJSON APIを取得

Posted at

Google Apps ScriptでJSONPlaceholderからデータを取得したので、忘れないようにメモとして記事にすることにしました。

開発環境

  • Google Apps Script

内容

  • JSONPlaceholderからデータを取得
  • GoogleSpreadSheetに書き込む

コード

class DataFetchError extends Error {}
class DataInvalidError extends Error {}

function myFunction() {
  const URL_TEXT = "https://jsonplaceholder.typicode.com/posts/1/comments";
  const response = UrlFetchApp.fetch(URL_TEXT);

  if (response.getResponseCode() !== 200) {
    throw new DataFetchError("データの取得に失敗しました");
  }

  const dataList = JSON.parse(response.getContentText());

  const spreadSheet = SpreadsheetApp.getActiveSpreadsheet();
  const sheet = spreadSheet.getActiveSheet();

  if (!Array.isArray(dataList) || dataList.length === 0) {
    throw new DataInvalidError("データリストが配列ではないか、空です");
  }

  const columnNames = Object.keys(dataList[0]);

  // シートに列名を追加
  sheet.appendRow(columnNames);

  // シートにデータ行を追加
  for (let data of dataList) {
    sheet.appendRow(Object.values(data));
  }
}
0
1
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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?