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

遍历谷歌表格生成不含空值的动态JSON API请求

解决方案

核心思路

  1. 构建原始JSON对象:先根据谷歌表格表头和行数据,把每行转换成包含所有字段的原始对象(如果有需要转数组的列,比如逗号分隔的字符串,先处理成数组)。
  2. 递归清理空值:用通用函数cleanObject递归处理对象和数组,自动移除:
    • 对象中值为null、undefined、空字符串""的字段;
    • 数组中的空元素(包括空字符串、空对象/数组);
    • 清理后变为空的数组或对象字段(可根据API需求调整)。

完整代码示例

function convertToAPIRequests() {
  const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Data");
  const data = sheet.getDataRange().getValues();
  const headers = data[0];
  const requests = [];

  for (let i = 1; i < data.length; i++) {
    const row = data[i];
    const rawObj = {};
    // 1. 按表头映射行数据,处理特殊字段(比如转数组)
    for (let j = 0; j < headers.length; j++) {
      const header = headers[j];
      let value = row[j];
      // 示例:表头带"_list"后缀的列,按逗号分割并去除元素空格
      if (header.endsWith("_list") && typeof value === 'string') {
        value = value.split(',').map(item => item.trim());
      }
      rawObj[header] = value;
    }
    // 2. 清理空值,得到符合API要求的请求体
    const cleanedObj = cleanObject(rawObj);
    requests.push(cleanedObj);
  }

  // 输出日志验证结果,后续可替换为API调用逻辑
  console.log(JSON.stringify(requests, null, 2));
  // requests.forEach(req => {
  //   UrlFetchApp.fetch("你的API地址", {
  //     method: 'POST',
  //     contentType: 'application/json',
  //     payload: JSON.stringify(req)
  //   });
  // });
}

// 通用空值清理函数
function cleanObject(obj) {
  // 处理数组:过滤空元素并递归清理子元素
  if (Array.isArray(obj)) {
    const cleaned = obj
      .filter(item => {
        if (item == null || item === "") return false;
        // 递归判断嵌套对象/数组是否为空
        if (typeof item === 'object') {
          const subCleaned = cleanObject(item);
          return Array.isArray(subCleaned) ? subCleaned.length > 0 : Object.keys(subCleaned).length > 0;
        }
        return true;
      })
      .map(item => cleanObject(item));
    // 空数组返回undefined,让外层对象移除该字段
    return cleaned.length > 0 ? cleaned : undefined;
  }

  // 处理普通对象:遍历属性,保留有效值
  if (typeof obj === 'object' && obj !== null) {
    const cleaned = {};
    for (const key in obj) {
      if (!obj.hasOwnProperty(key)) continue;
      const value = cleanObject(obj[key]);
      // 只保留非空、非空对象/数组的属性
      if (value != null && value !== "") {
        if (typeof value === 'object') {
          if (Array.isArray(value)) {
            if (value.length > 0) cleaned[key] = value;
          } else {
            if (Object.keys(value).length > 0) cleaned[key] = value;
          }
        } else {
          cleaned[key] = value;
        }
      }
    }
    return cleaned;
  }

  // 基本类型直接返回
  return obj;
}

代码说明

  • 原始对象构建:遍历每行数据时,可根据字段特性做预处理(比如把逗号分隔的字符串转数组),确保原始数据结构符合API预期。
  • 空值清理逻辑:cleanObject函数递归处理嵌套结构,既清理数组内的空元素,又移除对象中的无效字段,完全适配你的需求。
  • API调用适配:清理后的cleanedObj可直接作为JSON请求体传入API调用,无需额外处理。

示例验证

假设表格某行数据如下:

nameemailtags_listagenotes
Alicealice@test.coma,,b,
  • 原始对象:
{
  "name": "Alice",
  "email": "alice@test.com",
  "tags_list": ["a", "", "b", ""],
  "age": "",
  "notes": ""
}
  • 清理后对象(符合API要求):
{
  "name": "Alice",
  "email": "alice@test.com",
  "tags_list": ["a", "b"]
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 15:45:33