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

如何用json_normalize将JSON转为pandas DataFrame?遇KeyError问题

解决JSON转pandas DataFrame的KeyError问题

你的错误原因很明确:data的顶层结构是包含customers数组的对象,addresses是customers数组内每个元素的子字段,直接用record_path='addresses'时,程序在顶层data里找不到这个键,所以抛出KeyError。

修正后的代码

import pandas as pd

data={
    "customers": [
        {
            "a": 'true',
            "addresses": [{"city": "Park"}],
            "c": { "address1": "200"},
            "d": "mail@gmail.com",
            "e": {"f": "sub"},
            "h": 100,
           
        }
    ]
}

# 正确的转换代码
df = pd.json_normalize(
    data['customers'],  # 先定位到包含目标字段的customers数组
    record_path='addresses',  # 每个customer下的地址数组
    meta=['h'],  # 需要关联的customer级字段
    record_prefix='adr_'
)

print(df)

运行结果

adr_city    h
0     Park  100

扩展:提取更多嵌套字段

如果需要提取其他嵌套字段(比如c.address1、e.f),可以在meta参数中使用列表形式指定路径:

df = pd.json_normalize(
    data['customers'],
    record_path='addresses',
    meta=['h', 'd', ['c', 'address1'], ['e', 'f']],
    record_prefix='adr_',
    meta_prefix='cust_'
)

print(df)

扩展后的结果

adr_city  cust_h        cust_d cust_c.address1 cust_e.f
0     Park     100  mail@gmail.com             200      sub

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 15:10:06