如何用Python将Excel数据转换为指定格式JSON?是否需用pandas?
表格转指定格式JSON的实现方法
问题描述
原始表格数据:
| food ID | name | ingredients | ingredient ID | amount | unit |
|---|---|---|---|---|---|
| 1 | rice | red | R1 | 10 | g |
| 1 | soup | blue | B1 | 20 | g |
| 1 | soup | yellow | Y1 | 30 | g |
期望转换为如下格式的JSON:
{ "data": [ { "name": "rice", "ingredients": [ { "name": "red", "ingredient_id": "R1", "amount": 10, "unit": "g" } ] }, { "name": "soup", "ingredients": [ { "name": "blue", "ingredient_id": "B1", "amount": 20, "unit": "g" }, { "name": "yellow", "ingredient_id": "Y1", "amount": 30, "unit": "g" } ] } ] }
是否需要pandas?
既可以用pandas快速实现,也可以用纯Python代码完成转换,无需依赖第三方库,以下是两种方案:
方案一:使用pandas(推荐,代码更简洁)
pandas的分组功能可以很方便地按食物名称聚合配料数据,步骤如下:
- 读取表格数据(这里假设数据已加载为DataFrame,也可以从csv/excel读取)
- 按
name分组,将每组的配料信息整理为字典列表 - 构造目标JSON结构并输出
代码示例:
import pandas as pd import json # 原始表格数据构造DataFrame data = [ [1, 'rice', 'red', 'R1', 10, 'g'], [1, 'soup', 'blue', 'B1', 20, 'g'], [1, 'soup', 'yellow', 'Y1', 30, 'g'] ] df = pd.DataFrame(data, columns=['food ID', 'name', 'ingredients', 'ingredient ID', 'amount', 'unit']) # 分组并整理配料 result = {'data': []} for name, group in df.groupby('name'): ingredients = [] for _, row in group.iterrows(): ingredients.append({ 'name': row['ingredients'], 'ingredient_id': row['ingredient ID'], 'amount': row['amount'], 'unit': row['unit'] }) result['data'].append({'name': name, 'ingredients': ingredients}) # 输出JSON(ensure_ascii=False保证字符正常显示,indent格式化输出) print(json.dumps(result, ensure_ascii=False, indent=2))
方案二:纯Python实现(无第三方库依赖)
如果不想安装pandas,可以用字典来分组存储食物信息,手动遍历原始数据完成聚合:
代码示例:
import json # 原始表格数据 raw_data = [ {'food ID': 1, 'name': 'rice', 'ingredients': 'red', 'ingredient ID': 'R1', 'amount': 10, 'unit': 'g'}, {'food ID': 1, 'name': 'soup', 'ingredients': 'blue', 'ingredient ID': 'B1', 'amount': 20, 'unit': 'g'}, {'food ID': 1, 'name': 'soup', 'ingredients': 'yellow', 'ingredient ID': 'Y1', 'amount': 30, 'unit': 'g'} ] # 用字典临时存储每个食物的配料 food_map = {} for item in raw_data: food_name = item['name'] if food_name not in food_map: food_map[food_name] = [] food_map[food_name].append({ 'name': item['ingredients'], 'ingredient_id': item['ingredient ID'], 'amount': item['amount'], 'unit': item['unit'] }) # 构造目标结构 result = {'data': []} for name, ingredients in food_map.items(): result['data'].append({'name': name, 'ingredients': ingredients}) # 输出JSON print(json.dumps(result, ensure_ascii=False, indent=2))
内容的提问来源于stack exchange,提问作者studyhard
相关产品推荐
相关产品推荐

