You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用for循环导入JSON到Google Sheet仅重复首条数据该如何解决

错误原因
  • 取值逻辑错误:你在循环中写的getFinal = [final[i]]是取当前产品的第i个字段值,而非完整的单条产品数据,同时两层嵌套的循环逻辑完全多余,导致写入内容混乱
  • 写入方法误用:setValue仅能给选中范围填充单个值,你选中了多行多列的范围使用setValue,会导致整个范围都被填充同一个值,批量写入应该使用setValues方法
  • 未实现分页逻辑:当前代码仅硬编码拉取第1页数据,没有自动循环拉取所有页的逻辑
修正后代码
function dearAPI() {
  // 请替换为你自己的账号凭证
  const accountID = "你的accountID";
  const secret = "你的applicationkey";
  const limit = 10; // 单页拉取条数,可根据需求调整
  let pageNumber = 1;
  let allProducts = [];
  let hasNextPage = true;

  // 分页拉取所有产品数据
  while (hasNextPage) {
    const response = UrlFetchApp.fetch(
      `https://inventory.dearsystems.com/externalapi/v2/product?page=${pageNumber}&limit=${limit}`,
      {
        method: "get",
        headers: {
          "api-auth-accountid": accountID,
          "api-auth-applicationkey": secret,
        },
        contentType: "application/json"
      }
    );
    const json = JSON.parse(response.getContentText());
    const currentPageProducts = json.Products || [];
    allProducts = allProducts.concat(currentPageProducts);
    // 判断是否还有下一页
    hasNextPage = currentPageProducts.length === limit;
    pageNumber++;
  }

  if (allProducts.length === 0) {
    SpreadsheetApp.getUi().alert("未拉取到任何产品数据");
    return;
  }

  const sheet = SpreadsheetApp.getActiveSheet();
  // 写入表头
  const headers = [Object.keys(allProducts[0])];
  sheet.getRange(1, 1, headers.length, headers[0].length).setValues(headers);
  // 整理所有产品为二维数组
  const productRows = allProducts.map(product => Object.values(product));
  // 批量写入所有产品数据
  sheet.getRange(2, 1, productRows.length, productRows[0].length).setValues(productRows);
}
功能说明
  • 自动分页拉取:会从第1页开始循环拉取,直到拉完最后一页的所有产品数据
  • 批量写入优化:所有数据先整理为统一的二维数组,最后仅调用一次表格写入接口,运行效率更高,不会出现重复写入同一值的问题
  • 异常兼容:拉取到空数据时会弹出提示,避免脚本报错

内容的提问来源于stack exchange,提问作者Victoria

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 16:15:03