カソ研は、過疎地の暮らしと学びを応援します。


気象庁の過去データをスプレッドシートに反映する


スプレッドシートのシート名をsetにする。

gasのエディタにこれを貼る。

function jsonToSpreadsheet() {
  // スプレッドシートを取得
  const spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
  // シートを取得(新しいシートを作成する場合は getSheetByName を createSheet に変更)
  const sheet = spreadsheet.getSheetByName('set');
  const array = [];

  for (let fy=2022;fy<=2023;fy++){
    for(let month=1;month<=12;month++){
     array.push(download_kishou_data(47765,fy,month));
     console.log(fy+"年"+month+"月");
    }
  }

  const dataArray = array.flat();
  // 一度にセルに書き込み
  const range = sheet.getRange(1, 1, dataArray.length, dataArray[0].length);
  range.setValues(dataArray);
  range.removeDuplicates();
  range.sort({column: 2, ascending: false});

}


function download_kishou_data(locate,year,month){
  const json_Data = download_json(locate,year,month);
     // 二次元配列用のデータ
  const dataArray = [['地点', '年月日', '項目', '値']];

  // JSONデータを解析して二次元配列に追加
  for (let locate in json_Data) {
    const dates = json_Data[locate];
    for (const date in dates) {
      const item = dates[date];
      for (const key in item) {
        const value = item[key];
        dataArray.push([locate, new Date(date), key, value]);
      }
    }
  }
  return dataArray;
}

function download_json(locate,year,month) {

  url = `https://api.cultivationdata.net/past?no=${locate}&year=${year}&month=${month}`;
  try{
  const res = UrlFetchApp.fetch(url).getContentText();
  const json_data = JSON.parse(res);
  return json_data;}catch{
    console.log("urlがないよ")

  }
    
}

そして実行!

シート名setにデータが反映されたら成功です!

Follow me!


PAGE TOP