You need to enable JavaScript to run this app. 使用pd.json_normalize解析嵌套JSON时提取periods字段生成独立DataFrame的方法
优惠活动
大模型
产品
解决方案
定价
更多

使用pd.json_normalize解析嵌套JSON时提取periods字段生成独立DataFrame的方法

嵌套JSON中periods列表解析生成独立DataFrame的实现方案

示例嵌套JSON结构

data = {
    "results": [
        {
            "components": [
                {
                    "times": {
                        "periods": [
                            {
                                "fromDayOfWeek": 0,
                                "fromHour": 12,
                                "fromMinute": 0,
                                "toDayOfWeek": 4,
                                "toHour": 21,
                                "toMinute": 0,
                                "id": 156589,
                                "periodId": 20855
                            }
                        ]
                    }
                }
            ]
        }
    ]
}

当前解析卡点

  • 已可正常对results、components两层嵌套列表完成解析,生成对应DataFrame
  • 已尝试的解析代码:df = pd.json_normalize(data, record_path = ['results','components'])
  • 核心障碍:路径仅停留在components层级,未覆盖中间的times字典节点,无法定位到最下层的periods列表

可行实现方案

方案1:补全json_normalize的record_path完整路径

record_path参数支持沿着嵌套结构的字典、列表层级逐层追溯,只需把从最外层到目标periods列表的完整路径写入参数,即可直接生成包含periods全字段的独立DataFrame:

import pandas as pd
df_periods = pd.json_normalize(
    data,
    record_path=['results', 'components', 'times', 'periods']
)

生成的DataFrame会完整提取periods下的所有字段:fromDayOfWeek、fromHour、fromMinute、toDayOfWeek、toHour、toMinute、id、periodId。如果需要附带上层溯源字段(如所属组件标识),可配合meta参数指定需要提取的上层信息。

方案2:逐层遍历提取periods集合(容错性更强)

如果实际返回的JSON存在层级缺失(比如某条component无times节点、times下无periods节点),直接硬写路径容易触发KeyError中断流程,此时可先遍历攒取所有periods元素,再生成DataFrame:

all_periods = []
# 遍历results层,无results时默认取空列表避免报错
for result in data.get('results', []):
    # 遍历components层,无components时默认取空列表避免报错
    for component in result.get('components', []):
        # 校验times、periods节点存在后再提取
        if 'times' in component and 'periods' in component['times']:
            all_periods.extend(component['times']['periods'])
# 生成最终DataFrame
df_periods = pd.json_normalize(all_periods)

适用场景说明

  • 方案1适配结构完全规整的JSON返回,代码量最少,一行配置即可完成解析
  • 方案2适配生产环境的非标准化返回数据,可规避个别异常节点导致的解析中断

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.30 15:06:04