C#/JavaScript 如何将含父子数组的JSON字符串拆分为单子女父对象
嵌套子女数组的JSON扁平化拆分方案
需求说明
需要将包含父子嵌套结构的JSON数组,拆分为每个对象仅携带单个子女的平铺对象;特殊处理子女字段为null的场景:直接保留原对象不做拆分。此前公开搜索未找到匹配的现成处理方案,需要自行实现对应处理逻辑。
输入JSON结构
[{ "Father-Name" : "Jack", "Mother-Name" : "Rose", "Children": [{ "Name" : "Lmao" }, {"Name" : "Lol"}] },{ "Father-Name" : "Donald", "Mother-Name" : "Melissa", "Children": null }]
预期输出结构
[{ "Father-Name" : "Jack", "Mother-Name" : "Rose", "Children": { "Name" : "Lmao" } },{ "Father-Name" : "Jack", "Mother-Name" : "Rose", "Children": {"Name" : "Lol"} },{ "Father-Name" : "Donald", "Mother-Name" : "Melissa", "Children": null }]
核心实现逻辑
处理流程可拆解为3个步骤:
- 遍历原始JSON数组中的每一个父对象
- 读取当前父对象的
Children字段做分支判断:- 如果字段值为
null、或是非数组类型,直接将当前父对象整体加入结果集 - 如果字段值为数组,遍历数组内的每一个子女元素,基于原父对象的所有属性拷贝生成全新对象,将新对象的
Children字段替换为当前遍历到的单个子女元素,再加入结果集
- 如果字段值为
- 全量遍历完成后,直接返回组装好的结果集即可
参考实现(JavaScript版本)
// 原始输入JSON const rawData = [ { "Father-Name" : "Jack", "Mother-Name" : "Rose", "Children": [{ "Name" : "Lmao" }, {"Name" : "Lol"}] }, { "Father-Name" : "Donald", "Mother-Name" : "Melissa", "Children": null } ]; // 扁平化拆分处理 const result = rawData.flatMap(parent => { // 处理Children非数组的场景(含null值) if (!Array.isArray(parent.Children)) { return [parent]; } // 处理Children为数组的场景,每个子女生成独立的父对象条目 return parent.Children.map(singleChild => ({ ...parent, Children: singleChild })); }); // 打印格式化后的结果 console.log(JSON.stringify(result, null, 2));
内容的提问来源于stack exchange,提问作者MTLC
相关产品推荐
相关产品推荐

