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

Voiceflow中修改Google Sheets JS函数以获取所有工作表数据

解决Voiceflow中获取Google Sheets所有工作表数据及response.json is not a function错误问题

错误原因分析

response.json is not a function 是因为Voiceflow环境中,HTTP请求返回的可能是已自动解析完成的JSON对象,而非标准Fetch API的Response实例,此时调用.json()自然会报错。

解决方案1:一次性获取所有工作表数据

通过Google Sheets API的spreadsheets.get接口,配合includeGridData=true参数直接拉取全表数据,同时兼容Voiceflow的响应格式:

async function getAllSheetsData() {
  const spreadsheetId = "你的电子表格ID";
  const apiKey = "你的Google Sheets API密钥";
  
  // 请求全表数据(包含所有工作表)
  const response = await fetch(`https://sheets.googleapis.com/v4/spreadsheets/${spreadsheetId}?includeGridData=true&key=${apiKey}`);
  
  // 兼容Voiceflow的响应格式:判断是否需要手动解析JSON
  const rawData = typeof response.json === 'function' ? await response.json() : response;
  
  // 提取每个工作表的名称和数据
  return rawData.sheets.map(sheet => {
    const sheetName = sheet.properties.title;
    // 提取工作表的有效行数据(过滤空行)
    const rows = sheet.data[0].rowData.map(row => 
      row.values.map(cell => cell.formattedValue || cell.userEnteredValue?.stringValue || "")
    ).filter(row => row.some(cell => cell));
    
    return { sheetName, data: rows };
  });
}

解决方案2:分页式获取(避免大数据量单次请求截断)

如果全表数据量过大,可先获取所有工作表名称,再逐个拉取单表数据,降低单次请求负载:

async function getAllSheetsDataPaginated() {
  const spreadsheetId = "你的电子表格ID";
  const apiKey = "你的Google Sheets API密钥";
  
  // 第一步:获取所有工作表名称
  const sheetsResp = await fetch(`https://sheets.googleapis.com/v4/spreadsheets/${spreadsheetId}?key=${apiKey}`);
  const sheetsInfo = typeof sheetsResp.json === 'function' ? await sheetsResp.json() : sheetsResp;
  const sheetNames = sheetsInfo.sheets.map(sheet => sheet.properties.title);
  
  // 第二步:并行拉取每个工作表的数据
  return Promise.all(sheetNames.map(async name => {
    const dataResp = await fetch(`https://sheets.googleapis.com/v4/spreadsheets/${spreadsheetId}/values/${name}?key=${apiKey}`);
    const sheetData = typeof dataResp.json === 'function' ? await dataResp.json() : dataResp;
    
    return { sheetName: name, data: sheetData.values || [] };
  }));
}

注意事项

  • 确保已在Google Cloud Console中启用Google Sheets API,并配置好API密钥(私有表格需使用OAuth 2.0授权)。
  • 若工作表数据量极大,建议指定具体数据范围(如${name}!A1:Z1000)替代全表拉取,提升性能。
  • Voiceflow中需将函数设为async类型,确保异步逻辑正常执行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 17:33:11