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

使用pd.json_normalize展平多嵌套列表JSON报KeyError问题求解

错误原因

pd.json_normalize的record_path参数传入列表时,代表嵌套路径的层级顺序,你写的['Comments','ManyActionDateTimes']会被解析为:从根节点先取Comments字段,再在Comments的子元素中查找ManyActionDateTimes字段。但你的Comments子元素仅包含Comment和DateInserted两个字段,不存在目标键,因此触发KeyError。

解决方案

你有两个独立的嵌套列表,需要分两次调用json_normalize分别展开,再按公共字段合并即可,以下是可直接运行的代码:

import pandas as pd

# 原始JSON数据
jframe = [{"LoadRef": 0,
            "BookedDate": "2021-10-13T01:15:54.287Z",
            "EndDateTime": "2021-10-13T01:15:54.287Z",
            "Duration": "string",
            "Mp": True,
            "ManyActionDateTimes": [
            {
            "EventTime": "2021-10-13T01:15:54.287Z",
            "Type": "string",
            "Vehicle": "string"
            }
            ],
            "Finished": True,
            "Comments": [
            {
            "Comment": "string",
            "DateInserted": "2021-10-13T01:15:54.287Z"
            }
            ],
            "Company": "string",
            "SiteCode": 0,
            "Source": "string"
            }]

# 提取公共非嵌套字段
common_cols = [k for k in jframe[0].keys() if k not in ['ManyActionDateTimes', 'Comments']]

# 分别展开两个嵌套列表
df_action = pd.json_normalize(jframe, record_path='ManyActionDateTimes', meta=common_cols)
df_comment = pd.json_normalize(jframe, record_path='Comments', meta=common_cols)

# 合并两个展开结果
# 场景1:两个列表无对应关系,取笛卡尔积
jdf = df_action.merge(df_comment, on=common_cols, how='cross')

# 场景2:两个列表同组内按顺序一一对应,按序号合并即可
# df_action['row_idx'] = df_action.groupby(common_cols).cumcount()
# df_comment['row_idx'] = df_comment.groupby(common_cols).cumcount()
# jdf = df_action.merge(df_comment, on=common_cols+['row_idx'], how='outer').drop('row_idx', axis=1)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 03:45:03