如何从指定flat data生成目标结构的JSON数组对象
如何将扁平数据转换为指定结构的JSON数组
原始扁平数据
先整理你提供的原始数据(清理输入失误的多余标点与空格):
exco, business, product 10, Europe, shampooA 10, USA, shampooB 20, India, watch 30, china, fans
修正后的目标JSON结构
你给出的目标JSON存在语法错误(如缺少字段、括号不匹配),修正后的正确结构如下:
[ { "exco": 10, "Businesses": [ {"business": "Europe", "Products": [{"product": "shampooA"}]}, {"business": "USA", "Products": [{"product": "shampooB"}]} ] }, { "exco": 20, "Businesses": [{"business": "India", "Products": [{"product": "watch"}]}] }, { "exco": 30, "Businesses": [{"business": "china", "Products": [{"product": "fans"}]}] } ]
转换思路与实现
核心逻辑是按exco字段分组,将同exco的业务与产品数据归到同一对象的Businesses数组中,以下是两种常用语言的实现:
JavaScript实现
// 模拟解析后的扁平数据数组(实际场景可通过CSV解析库读取原始数据) const flatData = [ { exco: 10, business: 'Europe', product: 'shampooA' }, { exco: 10, business: 'USA', product: 'shampooB' }, { exco: 20, business: 'India', product: 'watch' }, { exco: 30, business: 'china', product: 'fans' } ]; // 按exco分组处理 const groupedMap = {}; flatData.forEach(item => { const excoKey = item.exco; // 初始化当前exco的分组结构 if (!groupedMap[excoKey]) { groupedMap[excoKey] = { exco: excoKey, Businesses: [] }; } // 将业务与产品数据添加到对应分组 groupedMap[excoKey].Businesses.push({ business: item.business, Products: [{ product: item.product }] }); }); // 转换为目标数组格式 const result = Object.values(groupedMap); console.log(JSON.stringify(result, null, 2));
Python实现
import json # 模拟解析后的扁平数据列表 flat_data = [ {"exco": 10, "business": "Europe", "product": "shampooA"}, {"exco": 10, "business": "USA", "product": "shampooB"}, {"exco": 20, "business": "India", "product": "watch"}, {"exco": 30, "business": "china", "product": "fans"} ] # 按exco分组 grouped_dict = {} for item in flat_data: exco = item["exco"] if exco not in grouped_dict: grouped_dict[exco] = {"exco": exco, "Businesses": []} grouped_dict[exco]["Businesses"].append({ "business": item["business"], "Products": [{"product": item["product"]}] }) # 转换为目标数组并输出 result = list(grouped_dict.values()) print(json.dumps(result, indent=2))
注意事项
- 原始数据中的冗余标点(如
20.的点)需提前清理,避免解析错误; - 需严格匹配目标JSON的字段大小写(如
Businesses、Products首字母大写); - 若原始数据为CSV格式,可使用对应语言的CSV解析工具(如JS的
papaparse、Python的csv模块)先完成数据读取,再执行分组逻辑。
内容的提问来源于stack exchange,提问作者ayyaan
相关产品推荐
相关产品推荐

