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

将嵌套JSON展开为DataFrame多列的实现问题

解决JSON嵌套数组列无法展开为DataFrame字段的问题

你遇到的核心问题是attributes字段为数组类型(空数组或仅含单个对象的数组),而pd.json_normalize默认只会展开嵌套对象结构,不会自动解析数组内的内容。以下是两种直接可行的解决方案:

方案一:提取数组元素后再展开

先从attributes数组中取出唯一对象(空数组返回None),再将提取后的对象展开为单独列,最后合并到原DataFrame:

import pandas as pd

response = {'data':     {'users': [ {'id': 12345, 'code': 'username1', 'attributes': []},
                                    {'id': 1460, 'code': 'username2', 'attributes': [{'id': 5, 'code': 'PD'}]}
                                 ]
                        }
            }

# 1. 解析基础用户数据
df = pd.json_normalize(response['data'], record_path=['users'])

# 2. 提取attributes数组中的第一个元素(空数组返回None)
df['attributes'] = df['attributes'].apply(lambda x: x[0] if len(x) > 0 else None)

# 3. 展开attributes对象并重命名列
attr_df = pd.json_normalize(df['attributes']).rename(
    columns={'id': 'attributes.id', 'code': 'attributes.code'}
)

# 4. 合并基础数据和展开后的属性列
result = pd.concat([df.drop('attributes', axis=1), attr_df], axis=1)
print(result)

运行后输出完全符合期望格式:

id      code  attributes.id attributes.code
0  12345  username1            NaN            None
1   1460  username2            5.0              PD

方案二:用explode展开数组后处理

利用explode将数组拆分为单行(空数组转为NaN),再展开嵌套对象:

import pandas as pd

response = {'data':     {'users': [ {'id': 12345, 'code': 'username1', 'attributes': []},
                                    {'id': 1460, 'code': 'username2', 'attributes': [{'id': 5, 'code': 'PD'}]}
                                 ]
                        }
            }

df = pd.json_normalize(response['data'], record_path=['users'])
# 展开attributes数组
df_exploded = df.explode('attributes', ignore_index=True)
# 展开嵌套对象并重命名列
attr_df = pd.json_normalize(df_exploded['attributes']).rename(
    columns={'id': 'attributes.id', 'code': 'attributes.code'}
)
# 合并结果
result = pd.concat([df_exploded.drop('attributes', axis=1), attr_df], axis=1)
print(result)

关键说明

pd.json_normalize的record_path参数用于指定要展开的数组(此处为users),但它不会递归展开数组类型的字段。因此必须先将attributes数组转换为单个对象或NaN,才能让json_normalize正确解析其中的嵌套字段。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 01:27:33