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

如何在Python中读取序列式格式化打印的JSON对象?

使用Python核心JSON库处理多格式化JSON对象

你提到的这种由多个格式化JSON对象组成的文件,完全可以用Python标准库中的json模块处理,核心是利用json.JSONDecoder.raw_decode()方法——它能从字符串中解析出第一个有效的JSON对象,并返回剩余未解析的内容,通过循环调用就能逐个处理所有对象,还能避免一次性加载整个文件。

方法1:一次性读取小文件

如果文件体积不大,可以一次性读取全部内容后逐个解析:

import json

def load_multiple_json(file_path):
    decoder = json.JSONDecoder()
    with open(file_path, 'r', encoding='utf-8') as f:
        content = f.read()
    
    current_pos = 0
    content_length = len(content)
    while current_pos < content_length:
        try:
            obj, current_pos = decoder.raw_decode(content, current_pos)
            yield obj
        except json.JSONDecodeError:
            # 跳过空白字符(换行、空格等)
            current_pos += 1

# 调用示例
for json_obj in load_multiple_json("your_data.json"):
    print(json_obj)

方法2:流式处理大文件

如果文件很大,不想一次性加载到内存,可以逐行读取并维护缓冲区,逐步解析:

import json

def stream_multiple_json(file_path):
    decoder = json.JSONDecoder()
    buffer = ""
    
    with open(file_path, 'r', encoding='utf-8') as f:
        for line in f:
            buffer += line
            # 尝试从缓冲区解析对象,直到无法解析(说明缓冲区内容不足)
            while True:
                try:
                    obj, pos = decoder.raw_decode(buffer)
                    yield obj
                    # 更新缓冲区为剩余未解析的内容
                    buffer = buffer[pos:]
                except json.JSONDecodeError:
                    break

# 调用示例
for json_obj in stream_multiple_json("large_data.json"):
    print(json_obj)

原理说明

raw_decode()方法会自动忽略输入字符串开头的空白字符,所以即使多个JSON对象之间有换行、空格或空行,也能正常解析。每次解析出一个对象后,我们更新当前位置或缓冲区,继续处理剩余内容,直到所有对象解析完成。

这种方式不需要修改原始文件的格式(保留了格式化JSON的可读性),也无需依赖第三方库,同时支持大文件的流式处理,避免了一次性加载整个文件的内存压力。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 21:13:10