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

如何用pandas json_normalize转JSON为CSV并保留解析树上层变量

JSON转CSV时保留深层数据与上层关键变量的解决方法

当使用pandas的json_normalize提取JSON深层节点ext_inspera_candidateResponses的数据时,无法同步保留上层的ext_inspera_candidateId、ext_inspera_autoScore等关键字段,直接添加meta="ext_inspera_candidateId"参数会导致对应列数据为空。

解决思路

核心是为meta参数指定字段的完整层级路径。由于record_path指向的是多层嵌套的深层节点,json_normalize需要明确知道上层字段所在的层级位置,而非仅字段名。

修改后的代码示例

import os
import pandas as pd
import json

os.chdir("/path/to/directory")

with open("json_file.json") as json_file:
    jd = json.load(json_file)

output = pd.json_normalize(
    jd,
    record_path=["ext_inspera_candidates", "result", "ext_inspera_questions", "ext_inspera_candidateResponses"],
    # 为每个上层关键变量指定完整层级路径,需匹配你的JSON实际结构
    meta=[
        ["ext_inspera_candidates", "ext_inspera_candidateId"],
        ["ext_inspera_candidates", "result", "ext_inspera_autoScore"]
    ]
)

output.to_csv("json_conversion_output.csv", index=False)

关键说明

  • 每个meta字段用列表形式指定从根节点到目标字段的完整路径,确保json_normalize能准确定位到上层变量;
  • 请根据你的JSON实际结构调整路径,比如如果ext_inspera_autoScore的层级不同,对应修改列表中的路径节点;
  • 补充了原代码遗漏的import json模块,避免json.load执行报错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 15:42:41