如何用Python将含数组键的JSON文件转换为两张关联的Excel工作表
代码调整方案
以下是可直接运行的调整后代码:
import json import pandas as pd # 读取JSON文件 with open('C:/Users/DELL-PC/Desktop/sample.json', encoding="utf8") as json_file: data = json.load(json_file) # 生成企业信息表 company_list = [item['information'] for item in data] df_company = pd.DataFrame(company_list) # 可选:去除所有字段前后的多余空格 df_company = df_company.apply(lambda x: x.str.strip() if x.dtype == "object" else x) # 生成带关联字段的用户信息表 user_list = [] for item in data: # 取当前企业的关联编号 member_no = item['information']['Member_No'].strip() # 遍历当前企业下的所有用户,追加关联字段 for user in item['users']: user['关联企业Member_No'] = member_no user_list.append(user) df_user = pd.DataFrame(user_list) # 可选:去除所有字段前后的多余空格 df_user = df_user.apply(lambda x: x.str.strip() if x.dtype == "object" else x) # 将两张表写入同一个Excel的不同工作表 with pd.ExcelWriter('C:/Users/DELL-PC/Desktop/Test.xlsx') as writer: df_company.to_excel(writer, sheet_name='企业信息表', index=False) df_user.to_excel(writer, sheet_name='用户信息表', index=False)
代码说明
- 企业信息表直接提取JSON每个条目下的
information字段内容,自动保留title、Member_No、Auth_Capital、Email四个所需字段 - 用户信息表遍历每个企业的
users数组,给每个用户追加当前企业的Member_No作为关联字段,保证两张表可通过该字段建立关联 - 写入时使用
pd.ExcelWriter将两个数据表分别写入不同的工作表,index=False参数用于避免导出多余的行序号列 - 不需要去除字段前后多余空格的话,可以删除两段带
apply的可选代码行
内容的提问来源于stack exchange,提问作者Med_Maliari
相关产品推荐
相关产品推荐

