如何用Python将含多工作表的XLSX转换为指定嵌套JSON?
解决方案
要实现将两个Excel工作表转换为指定的嵌套JSON结构,你可以用pandas灵活处理数据关联和结构构造,避免通用转JSON库的扁平化问题。以下是具体步骤和代码:
1. 依赖安装
首先确保安装必要的库:
pip install pandas openpyxl
2. 代码实现
假设你的Sheet 1包含外层字段(app_id_c、cust_id_n等),Sheet 2包含嵌套数组los_input_from_sas的内容,且两个表通过app_id_c字段关联:
import pandas as pd import json # 读取目标Excel文件 excel_file = pd.ExcelFile('你的文件路径.xlsx') # 加载两个工作表的数据 df_main = excel_file.parse('Sheet 1') df_nested = excel_file.parse('Sheet 2') # 预处理Sheet2:按关联字段分组,将每行数据转为字典并存储 nested_data = df_nested.groupby('app_id_c').apply( lambda x: x[['lsi_app_id_', 'lsi_cust_type_c']].to_dict('records') ).to_dict() # 构造最终嵌套JSON结构 final_json = [] for _, row in df_main.iterrows(): # 外层字段映射 item = { 'app_id_c': str(row['app_id_c']), 'cust_id_n': str(row['cust_id_n']), 'laa_app_a': str(row['laa_app_a']), 'laa_promc': str(row['laa_promc']), 'laa_branch': str(row['laa_branch']), 'laa_app_type_o': str(row['laa_app_type_o']), # 匹配对应的嵌套数据,无匹配则返回空数组 'los_input_from_sas': nested_data.get(row['app_id_c'], []) } final_json.append(item) # 输出格式化后的JSON print(json.dumps(final_json, indent=2, ensure_ascii=False))
3. 自定义调整
- 如果你的工作表字段名不同,直接修改代码中对应的字段字符串即可
- 若不需要批量处理(Sheet1只有一行数据),可以直接取
final_json[0]作为单个JSON对象输出 - 如果关联字段不是
app_id_c,替换groupby和get方法中的字段名即可
内容的提问来源于stack exchange,提问作者Shubham Trivedi
相关产品推荐
相关产品推荐

