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

UrlFetchApp.fetch()随机出现非有效JSON语法错误,求助解决

问题根源与修复方案

这个错误的核心原因是:你的请求偶尔没有拿到预期的JSON数据,反而收到了HTML内容(比如服务器错误页、访问拦截页),直接用JSON.parse()解析自然会报错。结合你的情况,大概率是目标服务器存在偶发的负载异常、速率限制,或者对无标识的请求偶尔拦截。

下面是针对性的修复步骤,直接替换你的代码即可:

1. 基础修复:状态码检查+异常捕获

先确保请求成功(状态码200),同时捕获解析失败的情况,避免脚本直接崩溃:

function fetch() {
  var url = "https://sum-app.net/projects/151546202312131392/download_data/kumu_json";
  var response = UrlFetchApp.fetch(url, {
    // 模拟浏览器请求头,降低被服务器拦截概率
    headers: {
      "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36"
    },
    muteHttpExceptions: true // 允许获取非200响应内容,方便排查
  });
  
  // 检查响应状态码
  if (response.getResponseCode() !== 200) {
    throw new Error(`请求失败,状态码:${response.getResponseCode()},响应片段:${response.getContentText().substring(0, 300)}`);
  }
  
  var source = response.getContentText();
  try {
    var data = JSON.parse(source);
    return data;
  } catch (e) {
    throw new Error(`JSON解析失败,响应片段:${source.substring(0, 300)}`);
  }
}

2. 进阶优化:添加重试机制

针对偶发的失败,自动重试几次(比如3次),减少手动刷新的麻烦:

function fetch() {
  var url = "https://sum-app.net/projects/151546202312131392/download_data/kumu_json";
  var maxRetries = 3;
  var retryDelay = 1000; // 重试间隔1秒

  for (var i = 0; i < maxRetries; i++) {
    try {
      var response = UrlFetchApp.fetch(url, {
        headers: {
          "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36"
        },
        muteHttpExceptions: true
      });

      if (response.getResponseCode() !== 200) {
        if (i < maxRetries - 1) {
          Utilities.sleep(retryDelay);
          continue;
        } else {
          throw new Error(`请求失败,状态码:${response.getResponseCode()}`);
        }
      }

      var source = response.getContentText();
      var data = JSON.parse(source);
      return data;

    } catch (e) {
      if (i < maxRetries - 1) {
        Utilities.sleep(retryDelay);
        continue;
      } else {
        throw new Error(`最终失败:${e.message}`);
      }
    }
  }
}

额外排查建议

  • 开启muteHttpExceptions: true后,失败时可以查看返回的HTML内容,判断是服务器内部错误、速率拦截还是需要验证,能更精准定位问题
  • 如果频繁触发错误,考虑降低请求频率,避免触发目标服务器的限流规则
  • 确认目标服务器是否更新了访问规则,是否需要添加API密钥等认证信息

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 02:23:16