Python将嵌套JSON拆分指定列导出为Excel的实现问题求助
嵌套JSON转指定字段Excel实现方案
你的原始JSON为两层嵌套结构:外层存储选区维度的公共属性,各政党得票明细存储在外层的by_party数组字段中,直接读取无法生成符合字段要求的一维表格,需要先将嵌套数据打平再导出。
操作步骤
安装依赖库
执行以下命令安装数据处理和Excel读写需要的第三方库:pip install pandas openpyxl运行转换代码
将以下代码保存为py文件,确认JSON文件本地路径正确后直接运行即可:
import json import pandas as pd # 配置本地文件路径 json_file_path = r'C:\Users\xsd\Downloads\gen_elec_sl.ec.results.2020.json' excel_output_path = r'C:\Users\xsd\Downloads\election_result_export.xlsx' # 加载原始JSON数据 with open(json_file_path, 'r', encoding='utf-8') as f: raw_election_data = json.load(f) # 扁平化嵌套数据,拼接为符合要求的行结构 processed_rows = [] for district_record in raw_election_data: # 提取外层选区公共字段 base_fields = { 'type': district_record['type'], 'timestamp': district_record['timestamp'], 'level': district_record['level'], 'ed_code': district_record['ed_code'], 'ed_name': district_record['ed_name'] } # 跳过缺失政党数据的异常条目 if 'by_party' not in district_record: continue # 遍历每个政党的得票数据,和公共字段拼接为单行 for party_record in district_record['by_party']: current_row = base_fields.copy() current_row.update({ 'vote_count': party_record['vote_count'], 'vote_percentage': party_record['vote_percentage'], 'seat_count': party_record['seat_count'], 'national_list_seat_count': party_record['national_list_seat_count'], 'party_code': party_record['party_code'], 'party_name': party_record['party_name'] }) processed_rows.append(current_row) # 按指定字段顺序生成表格并导出 target_columns = [ 'type', 'timestamp', 'level', 'ed_code', 'ed_name', 'vote_count', 'vote_percentage', 'seat_count', 'national_list_seat_count', 'party_code', 'party_name' ] result_df = pd.DataFrame(processed_rows, columns=target_columns) result_df.to_excel(excel_output_path, index=False, engine='openpyxl') print(f"转换完成,Excel文件已保存至:{excel_output_path}")
可选调整项
- 若需要将Unix时间戳转换为可读日期格式,修改
base_fields中timestamp的取值逻辑为:'timestamp': pd.to_datetime(district_record['timestamp'], unit='s') - 若文件存储路径有变化,直接修改
json_file_path和excel_output_path的配置值即可 - 导出的Excel会严格按照你要求的字段顺序排列,默认不生成多余的索引列
内容的提问来源于stack exchange,提问作者Snyder Fox
相关产品推荐
相关产品推荐

