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

加载多行JSON文件到Pandas DataFrame时read_json报错问题咨询

Pandas加载多行JSON文件报错的解决方法

报错原因说明

  • 未加lines=True触发的ValueError: Mixing dicts with non-Series may lead to ambiguous ordering报错,是因为待加载的文件是JSON Lines格式(每一行是一个独立的JSON对象),不是顶层为数组或单个对象的标准JSON结构,pandas默认的标准JSON解析逻辑无法适配该格式。
  • 添加lines=True后仍触发ValueError: Expected object or value报错,通常是文件路径错误、文件中存在空行、存在格式不合法的JSON行三类原因导致。

解决步骤

步骤1:校验文件路径与内容合法性

首先确认文件路径正确、内容格式符合预期,可运行以下代码验证:

import os
# 校验文件路径是否正确,输出为True则路径合法
print(os.path.exists('data.json'))
# 打印文件前5行内容,排查是否有空行、格式异常行
with open('data.json', 'r', encoding='utf-8') as f:
    for _ in range(5):
        print(repr(f.readline()))

步骤2:逐行过滤加载适配异常场景

如果存在空行、非法JSON行的情况,不要直接使用pd.read_json,改用逐行解析过滤的方式加载:

import pandas as pd
import json

parsed_data = []
with open('data.json', 'r', encoding='utf-8') as f:
    for line in f:
        stripped_line = line.strip()
        # 跳过空行
        if not stripped_line:
            continue
        # 仅加载格式合法的JSON行
        try:
            parsed_data.append(json.loads(stripped_line))
        except json.JSONDecodeError:
            # 可自行添加日志打印非法行内容,排查格式问题
            pass

df_raw = pd.DataFrame(parsed_data)

步骤3:适配全文件单JSON数组场景

如果你的文件不是JSON Lines格式,只是单个JSON数组做了格式化换行展示,用以下方式加载:

import pandas as pd
import json

with open('data.json', 'r', encoding='utf-8') as f:
    full_json = json.load(f)
# 可通过pd.json_normalize扁平化嵌套JSON结构
df_raw = pd.json_normalize(full_json)

补充说明

如果加载后存在嵌套结构的字段,可调用pd.json_normalize()方法对已加载的数据做扁平化处理,按需提取不同层级的字段值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 19:45:04