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

如何使用Pandas read_json(lines=True)忽略非JSON行?

问题解答

仅靠pandas.read_json()的参数组合无法实现忽略非JSON行的需求。

原因很明确:read_json()本身没有提供跳过格式无效行的参数,你用到的encoding_errors='ignore'只负责处理编码层面的错误,对JSON格式错误完全不起作用。哪怕尝试orient='records'这类参数,也只是指定JSON的结构类型,没法过滤掉非JSON内容的行。

要解决这个问题,得换个思路——先手动逐行读取文件,过滤出能正常解析的JSON行,再转成DataFrame,示例代码如下:

import pandas as pd
import json

valid_lines = []
with open('test.json', 'r', encoding='utf-8') as f:
    for line in f:
        line = line.strip()
        if not line:
            continue
        try:
            json.loads(line)
            valid_lines.append(line)
        except json.JSONDecodeError:
            # 跳过解析失败的非JSON行
            continue

# 把有效行拼接成符合lines格式的字符串,再用read_json读取
df = pd.read_json('\n'.join(valid_lines), lines=True)

这样就能自动忽略掉Time out这类无效行,只保留合法的JSON记录生成DataFrame。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 13:22:09