Google Script中如何提取嵌套JSON数组的指定字段?
解决Google Script中提取嵌套JSON数组字段的问题
先明确核心思路
要提取嵌套JSON里的目标字段,关键是精准匹配层级路径,同时做好空值/非数组的容错处理。以下结合常见场景给出解决方案:
示例输入JSON结构(匹配你的需求场景)
假设你的JSON数据结构如下(若实际结构不同,只需对应调整路径):
{ "records": [ { "details": [ { "start": "2024-05-01", "position": "Shelf-3", "out_Quantity": { "quantity": 50, "unit": "box" } }, { "start": "2024-05-02", "position": "Shelf-5", "out_Quantity": { "quantity": 30, "unit": "box" } } ] } ] }
正确提取字段的Google Script代码
function extractTargetFields() { // 替换为你的实际JSON数据(比如通过UrlFetchApp获取后解析的对象) const rawJson = UrlFetchApp.fetch("你的数据源URL").getContentText(); const jsonData = JSON.parse(rawJson); const result = []; // 遍历顶层数组(这里是records,根据你的实际结构调整) jsonData.records.forEach(topItem => { // 先判断嵌套数组是否存在且为数组类型,避免报错 if (topItem.details && Array.isArray(topItem.details)) { // 遍历嵌套的details数组 topItem.details.forEach(nestedItem => { // 提取目标字段,用可选链?.避免字段缺失时报错 const item = { start: nestedItem.start, position: nestedItem.position, quantity: nestedItem.out_Quantity?.quantity }; result.push(item); }); } }); // 输出结果到日志,或后续处理 Logger.log(result); return result; }
常见问题排查
- 字段名大小写不匹配:Google Script是大小写敏感的,确认
start/position/out_Quantity/quantity的拼写、大小写完全和JSON一致。 - 层级路径错误:比如你直接从顶层对象取
start,而没有先进入嵌套数组(比如示例中的details数组)。 - 未做空值判断:如果嵌套数组可能为空或不存在,必须先判断
Array.isArray(),否则遍历会抛出异常。 - 缺失可选链处理:如果部分对象没有
out_Quantity字段,使用?.运算符可以返回undefined而不是直接崩溃。
内容的提问来源于stack exchange,提问作者Kim Hinge
相关产品推荐
相关产品推荐

