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

如何修改嵌套JSON转Pandas DataFrame代码,缺失字段返回null?

解决嵌套JSON转DataFrame时字段缺失报错的问题

这个场景太常见了——处理嵌套JSON数据时,总有个别条目会缺失某些字段,直接用键访问就会炸出KeyError。咱们可以用字典的get()方法来优雅解决,它支持指定字段不存在时的默认值,完美适配你的需求。

修改后的代码

import pandas as pd

records = []
for item in d["Data"]:
    records.append(
        {
            "Type": item.get("CoinInfo", {}).get("Type"),
            "Name": item.get("CoinInfo", {}).get("Name"),
            "SUPPLY": item.get("RAW", {}).get("USD", {}).get("SUPPLY"),
        }
    )

df = pd.DataFrame.from_records(records)
df.head()

为什么这样改?

  • dict.get(key, default) 会尝试获取指定键的值,如果键不存在,就返回你指定的default值。这里把内层的默认值设为空字典{},是为了避免外层字段缺失时,内层的.get()调用报错(比如某个item根本没有CoinInfo字段,直接写item["CoinInfo"].get("Type")还是会报错)。
  • 当字段完全缺失时,get()会返回None,Pandas会自动把None转换成DataFrame里的NaN(也就是你要的null)。

进阶优化:提取嵌套字段的通用函数

如果要提取的嵌套字段很多,反复写嵌套get()会很繁琐,可以写个小函数来复用逻辑:

def extract_nested_field(item, field_path):
    current = item
    for key in field_path:
        current = current.get(key, {})
        if not current:
            return None
    return current

# 调用示例
records = []
for item in d["Data"]:
    records.append(
        {
            "Type": extract_nested_field(item, ["CoinInfo", "Type"]),
            "Name": extract_nested_field(item, ["CoinInfo", "Name"]),
            "SUPPLY": extract_nested_field(item, ["RAW", "USD", "SUPPLY"]),
        }
    )

这样代码更整洁,后续加新字段也更方便。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 12:02:41