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

如何展平嵌套JSON数据?Pandas处理JSONDecodeError问题求助

处理嵌套JSON数据并扁平化DataFrame的解决方案

一、先解决JSON读取报错问题

你遇到的JSONDecodeError是因为部分行的JSON格式不合法(比如多余字符、未闭合的括号等),可以用逐行读取并过滤错误行的方式替代直接pd.read_json:

import pandas as pd
import json

data_list = []
with open("the_file.json", "r", encoding="utf-8") as f:
    for line_num, line in enumerate(f, 1):
        line = line.strip()
        if not line:
            continue
        try:
            data_list.append(json.loads(line))
        except json.JSONDecodeError as e:
            print(f"跳过格式错误的行 {line_num}: {e}")
df = pd.DataFrame(data_list)

二、展开嵌套列(以comments为例)

1. 单层嵌套列表(每个元素是字典)

如果comments是嵌套字典的列表,用json_normalize同时保留原表的其他列:

from pandas import json_normalize

# 展开comments列,保留原表所有其他列作为元数据
flattened_df = json_normalize(
    df.to_dict("records"),
    record_path="comments",
    meta=[col for col in df.columns if col != "comments"]
)

执行后,原表的每一行会根据comments里的元素数量拆分成多行,其他列的值会自动重复对应。

2. 多层嵌套数据

如果comments里的元素还有更深层的嵌套(比如包含replies这类子列表),可以逐层展开:

# 第一步:展开comments列
first_step = json_normalize(
    df.to_dict("records"),
    record_path="comments",
    meta=[col for col in df.columns if col != "comments"]
)

# 第二步:展开comments里的replies列(假设存在)
final_flattened = json_normalize(
    first_step.to_dict("records"),
    record_path="replies",
    meta=[col for col in first_step.columns if col != "replies"]
)

3. 处理空嵌套列表的情况

如果部分行的comments是空列表,上面的方法会自动跳过这些行。要保留这类数据,可以先标记空值再合并:

# 将空列表转为NaN
df["comments"] = df["comments"].apply(lambda x: x if len(x) > 0 else None)

# 展开非空的comments
non_empty_flatten = json_normalize(
    df.dropna(subset=["comments"]).to_dict("records"),
    record_path="comments",
    meta=[col for col in df.columns if col != "comments"]
)

# 合并空行数据
final_df = pd.concat([non_empty_flatten, df[df["comments"].isna()]]).reset_index(drop=True)

三、验证扁平化结果

执行完上述步骤后,你可以用final_df.columns查看所有列,确认是否所有嵌套字段都已展开为独立列,也可以用final_df.head()预览数据格式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 06:10:31