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

如何跳过pd.read_json(lines=True)读取时引发"ValueError: Unexpected character found when decoding object value"错误的JSON行

如何跳过pd.read_json(lines=True)读取时引发"ValueError: Unexpected character found when decoding object value"错误的JSON行

嘿,这个问题我太熟了!用pd.read_json(lines=True)读取JSON Lines格式文件时,只要有一行格式不对(比如截断、语法错误),整个读取就会直接炸掉。下面给你两个实用的解决方案,帮你轻松跳过那些有问题的行:

方法一:逐行验证后读取(通用版)

我们可以先手动逐行扫一遍文件,验证每行是不是有效的JSON,只保留没问题的行再传给pandas。这样既不会因为错误行中断流程,还能清楚看到哪些行出了问题:

import pandas as pd
import json

def load_clean_json_lines(file_path):
    valid_lines = []
    with open(file_path, 'r', encoding='utf-8') as f:
        for line_idx, line in enumerate(f, start=1):
            stripped_line = line.strip()
            # 先跳过空行
            if not stripped_line:
                continue
            try:
                # 尝试解析该行,验证JSON格式合法性
                json.loads(stripped_line)
                valid_lines.append(stripped_line)
            except json.JSONDecodeError as err:
                print(f"⚠️ 跳过第{line_idx}行,格式错误:{err}")
    
    # 把有效行拼接成JSON Lines格式的字符串,交给pandas读取
    return pd.read_json('\n'.join(valid_lines), lines=True)

# 调用函数读取你的比特币交易文件
df = load_clean_json_lines('btc_transactions.json')

方法二:用生成器流式处理(超大文件适配)

如果你的JSON文件特别大,不想把所有有效行都存在内存里,可以用生成器来流式传递有效行,内存占用会低很多:

import pandas as pd
import json

def valid_json_stream(file_path):
    with open(file_path, 'r', encoding='utf-8') as f:
        for line_idx, line in enumerate(f, start=1):
            stripped_line = line.strip()
            if not stripped_line:
                continue
            try:
                json.loads(stripped_line)
                yield stripped_line
            except json.JSONDecodeError as err:
                print(f"⚠️ 跳过第{line_idx}行,格式错误:{err}")

# 直接用生成器创建DataFrame
df = pd.read_json(valid_json_stream('btc_transactions.json'), lines=True)

为什么会出现这个错误?

拿你提供的示例来说,第二行的"consensus_time":"2013...是截断的,属于不完整的JSON结构,pandas解析时自然会触发错误。这类问题通常是文件生成时的bug(比如写入中途中断)导致的,跳过这些残缺行就能正常读取剩下的有效数据了。

备注:内容来源于stack exchange,提问作者TLeitzbach

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.16 11:55:29