You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中如何解析JSON数据?附代码及数据结构化处理需求

Python 解析JSON及对应表格数据处理方案

Python 标准库自带json模块,完全可以满足JSON数据解析、生成的需求,你提供的基础代码存在Windows路径转义、文件资源未自动回收的问题,以下是修正后的用法和对应业务需求的完整实现。

基础JSON读写正确写法

原代码直接写Windows路径的反斜杠会被识别为转义符,推荐用原生字符串搭配上下文管理器写法,自动处理文件开关:

import json

# 读取本地JSON文件
with open(r'C:\Users\Hello\Desktop\usecase2.json', encoding='utf-8') as f:
    data = json.load(f)
print(data)

# 写入JSON文件
with open(r'C:\Users\Hello\Desktop\output.json', 'w', encoding='utf-8') as f:
    # ensure_ascii=False避免中文被转义,indent=2格式化输出
    json.dump(output_data, f, ensure_ascii=False, indent=2)

注意:如果是解析接口返回的JSON字符串,直接用json.loads(json_str)即可,不需要走文件读取逻辑。

业务需求落地实现

针对你提到的三个表格处理需求,需要先安装Excel读写依赖:
pip install pandas openpyxl

实现逻辑完全匹配需求点:

  • 分别读取Excel内Raw Data(原始数据)、Desired Output(目标格式)两个工作表,以目标表的列顺序作为整理标准
  • 按Pur Lot字段做分组聚合,分组时保留空值行,每个Pur Lot下不管有多少条迭代数据都会完整归集,不会遗漏
  • 归集完成后直接生成以Pur Lot为顶级键的字典结构,导出为JSON文件存储全量数据

完整可运行代码:

import json
import pandas as pd

# 配置文件路径
excel_file_path = r'C:\Users\Hello\Desktop\待处理数据.xlsx'
json_output_path = r'C:\Users\Hello\Desktop\raw_data_full.json'
excel_output_path = r'C:\Users\Hello\Desktop\整理完成数据.xlsx'

# 读取两个工作表数据
raw_data = pd.read_excel(excel_file_path, sheet_name='Raw Data')
target_columns = pd.read_excel(excel_file_path, sheet_name='Desired Output').columns.tolist()

# 按Pur Lot分组归集全量数据
json_output = {}
for pur_lot, lot_group in raw_data.groupby('Pur Lot', dropna=False):
    # 按目标字段顺序整理,空值替换为空字符串避免格式异常
    formatted_records = lot_group[target_columns].fillna('').to_dict('records')
    json_output[str(pur_lot)] = formatted_records

# 导出全量JSON文件
with open(json_output_path, 'w', encoding='utf-8') as f:
    json.dump(json_output, f, ensure_ascii=False, indent=2)

# 如需直接导出整理好的目标格式Excel,执行以下代码
all_formatted_rows = []
for records in json_output.values():
    all_formatted_rows.extend(records)
pd.DataFrame(all_formatted_rows, columns=target_columns).to_excel(excel_output_path, index=False)

常见问题说明

  • 分组时加dropna=False是为了避免Pur Lot字段为空的行被自动过滤,保证全量数据捕获
  • Pur Lot转字符串后作为JSON键,可避免数字类型键被自动转换、排序的问题
  • 如果原始数据存在合并单元格,读入后先做向下填充空值处理再分组即可,不会影响数据完整性

内容的提问来源于stack exchange,提问作者user19470665

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.28 05:09:20