在这种情况下如何使用GAS来创建字典

How to dictionary in this case with GAS?

本文关键字:创建 字典 GAS 何使用 这种情况下      更新时间:2023-09-26

我是一个新手,非本地…

function fetch_json() {
  var result = UrlFetchApp.fetch("https://api.ookami.me/v1/news/public?sport_id=1");
  var obj = JSON.parse(result.getContentText());
  var ss = SpreadsheetApp.openById("1ecv2r3qBEuHWyP4XH7FkGktQ7YHqegd7CztRoARzKac");
  var sheet = ss.getSheetByName("soccer");
  for (var n=0; n < 10; n++) {
    var news = json["news"][n];
    var a = news["id"];
    var b = news["title"];
    var c = news["summary"];
    var d = news["media_name"];
    var e = news["url"];
    var f = news["image"];
    var array = [a, b, c, d, e, f];
    var columnA = sheet.getRange(2, 1);
    var valuesA = columnA.getValues();
    var maxid = valuesA[0][0];
    if (a > maxid) {
      sheet.appendRow(array);
    }else{
      break
    }
    sheet.setColumnWidth(6, 120);
    var last_row = sheet.getLastRow();
     if (f != null) {
       var cell = sheet.getRange(last_row, 6);
       var image_cell = "=IMAGE('"" + f + "'", 1)";
       cell.setValue(image_cell);
       sheet.setRowHeight(last_row, 72);
  }else{
    sheet.setRowHeight(last_row, 72);
  }
  }
    sheet.autoResizeColumn(1);
    sheet.sort(1, false);
}

这是一个完整的代码。我想运行相同的功能简单地通过使用其他url到其他表。

var result= UrlFetchApp.fetch("https://api.ookami.me/v1/news/public?sport_id=1");

" sport_id = 1"→"sport_id = 2","sport_id = 3"…"sport_id = 37"。和

var sheet = ss.getSheetByName("soccer");

"足球"→"棒球"、"网球"……"此前sportsbusiness"(37张)。棒球:2 (id)、网球:3…此前sportsbusiness: 37

我这样想象

function a () {
    //I don't know the code I want to write 
  function fetch_json ()
}

有可能吗?

我不懂"dictionary"方法,如果有其他方法,请教我。

如果我理解正确,您希望从不同的url获取数据,并根据运动将数据写入同一电子表格中的不同表格。我将首先为所有的运动定义一个对象:

var sportIds = {
  0: 'soccer',
  1: 'baseball',
  2: 'tennis',
  ...
  36: 'sportsbusiness'
};

在上面的对象中,键是url中的id,值是表名。然后,您可以循环遍历对象并使用以下命令获取/写入数据:

var urlBase = "https://api.ookami.me/v1/news/public?sport_id=";
for (var id in sportIds){
  var url = urlBase+id; // Generate the url using the id/key from the object
  var result = UrlFetchApp.fetch(url);
  var sheet = ss.getSheetByName(sportIds[id]);
  // write to the sheet as desired
}

在这里,您使用对象中的键生成url,并使用相应的值获得要写入的工作表。好像这样就行了。如果这不是你想要的,请评论