如何使用DataWeave将JSON中的数组字段拆分为对应多行?
如何拆分JSON中的数组字段为对应位置的多行对象
要实现这个需求,核心逻辑是遍历每个原始JSON对象,再针对数组的每个索引位置生成新对象——把两个数组对应索引的元素替换成字段值,同时保留其他字段的原始内容。下面用两种常用编程语言给出具体实现方案:
JavaScript 实现
// 解析输入的JSON字符串 const inputJson = `[ { "firstName": "John", "surname": "Smith", "primarySkills": ["presentation", "developer"], "secondarySkills": ["abc", "xyz"], "email": "js@email.com", "phone": "1234567890" }, { "firstName": "S", "surname": "D", "primarySkills": ["presentation"], "secondarySkills": ["developer"], "email": "js@email.com", "phone": "1234567890" } ]`; const inputData = JSON.parse(inputJson); const result = []; inputData.forEach(item => { const primarySkills = item.primarySkills; const secondarySkills = item.secondarySkills; // 处理数组长度不一致的情况:取两个数组的最大长度 const maxLength = Math.max(primarySkills.length, secondarySkills.length); for (let i = 0; i < maxLength; i++) { // 深拷贝原对象,避免修改原始数据 const newItem = {...item}; // 替换数组字段为对应索引的元素,超出长度则设为null newItem.primarySkills = primarySkills[i] ?? null; newItem.secondarySkills = secondarySkills[i] ?? null; result.push(newItem); } }); // 输出格式化后的结果 console.log(JSON.stringify(result, null, 4));
Python 实现
import json input_json = '''[ { "firstName": "John", "surname": "Smith", "primarySkills": ["presentation", "developer"], "secondarySkills": ["abc", "xyz"], "email": "js@email.com", "phone": "1234567890" }, { "firstName": "S", "surname": "D", "primarySkills": ["presentation"], "secondarySkills": ["developer"], "email": "js@email.com", "phone": "1234567890" } ]''' input_data = json.loads(input_json) result = [] for item in input_data: primary = item['primarySkills'] secondary = item['secondarySkills'] max_len = max(len(primary), len(secondary)) for i in range(max_len): # 深拷贝原对象 new_item = item.copy() # 替换字段值,索引超出数组长度时设为None new_item['primarySkills'] = primary[i] if i < len(primary) else None new_item['secondarySkills'] = secondary[i] if i < len(secondary) else None result.append(new_item) # 打印格式化后的JSON结果 print(json.dumps(result, indent=4))
关键注意点
- 深拷贝处理:示例中用了浅拷贝方式(JS的扩展运算符、Python的copy方法),如果原始对象包含嵌套对象,需要改用更彻底的深拷贝(比如JS的
JSON.parse(JSON.stringify(item)),Python的copy.deepcopy(item)),避免修改原始数据。 - 数组长度不一致:示例中取两个数组的最大长度,短数组对应位置补
null/None。你也可以根据需求调整逻辑,比如只处理到最短数组的长度,或者抛出错误提示长度不匹配。 - 字段替换:将原来的数组类型字段直接替换为对应索引的单个元素,确保新对象中这两个字段不再是数组。
内容的提问来源于stack exchange,提问作者user12277274
相关产品推荐
相关产品推荐

