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

如何在Python中将含数组的嵌套JSON转换为结构化DataFrame?

解决嵌套JSON转结构化DataFrame的方案

针对嵌套JSON中数组或嵌套对象字段无法展开的问题,用pandas.json_normalize结合explode是最直接的方案,以下分场景给出具体实现:

1. 基础场景:同时存在嵌套对象和数组字段

假设你的dados_ceaf结构示例如下:

dados_ceaf = [
    {
        "id": 1,
        "nome": "Projeto A",
        "fundamentacao": [
            {"codigo": "F1", "descricao": "Legislação X"},
            {"codigo": "F2", "descricao": "Norma Y"}
        ],
        "detalhes": {"valor": 10000, "prazo": "12 meses"}
    },
    {
        "id": 2,
        "nome": "Projeto B",
        "fundamentacao": [{"codigo": "F3", "descricao": "Resolução Z"}],
        "detalhes": {"valor": 5000, "prazo": "6 meses"}
    }
]

步骤1:展开顶层嵌套对象

用json_normalize直接处理顶层的嵌套对象(比如detalhes),自动将嵌套字段展开为父字段.子字段的格式:

import pandas as pd
from pandas import json_normalize

# 初始化并展开嵌套对象
df = json_normalize(dados_ceaf)

此时df的列会是:id, nome, fundamentacao, detalhes.valor, detalhes.prazo

步骤2:拆分数组字段并展开内部嵌套

先通过explode将数组字段(比如fundamentacao)的每个元素拆分为单独行,再用json_normalize展开数组内的嵌套对象:

# 拆分数组字段,生成新行
df_exploded = df.explode('fundamentacao', ignore_index=True)

# 展开数组内的嵌套对象,并合并到原DataFrame
df_final = pd.concat([
    df_exploded.drop('fundamentacao', axis=1),
    json_normalize(df_exploded['fundamentacao'])
], axis=1)

最终df_final会是完全结构化的表格,每个字段都是扁平的单列。

2. 复杂多层嵌套场景

如果数组内部还有嵌套数组(比如fundamentacao里的元素又包含数组字段),可以递归执行explode+json_normalize:

def flatten_nested_df(df, nested_col):
    # 拆分数组字段
    df_exploded = df.explode(nested_col, ignore_index=True)
    # 展开嵌套对象
    nested_df = json_normalize(df_exploded[nested_col])
    # 合并并移除原嵌套列
    df_merged = pd.concat([df_exploded.drop(nested_col, axis=1), nested_df], axis=1)
    # 检查是否还有剩余嵌套数组字段
    nested_cols = [col for col in df_merged.columns if isinstance(df_merged[col].iloc[0], list)]
    if nested_cols:
        return flatten_nested_df(df_merged, nested_cols[0])
    return df_merged

# 调用递归函数处理多层嵌套
df_final = flatten_nested_df(df, 'fundamentacao')

关键说明

  • 单独用explode只会拆分数组为多行,但不会展开数组内的嵌套对象,必须配合json_normalize完成字段扁平化。
  • 如果部分字段存在缺失值,可在explode时添加dropna=False保留空行,根据业务需求调整。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 04:39:17