遍历谷歌表格生成不含空值的动态JSON API请求
解决方案
核心思路
- 构建原始JSON对象:先根据谷歌表格表头和行数据,把每行转换成包含所有字段的原始对象(如果有需要转数组的列,比如逗号分隔的字符串,先处理成数组)。
- 递归清理空值:用通用函数
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调用,无需额外处理。
示例验证
假设表格某行数据如下:
| name | tags_list | age | notes | |
|---|---|---|---|---|
| Alice | alice@test.com | a,,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
相关产品推荐
相关产品推荐

