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

如何高效追加字典为gzip压缩JSON对象至JSON文件

实现gzip压缩的JSON数据高效追加与读取

针对大文件下JSON数据追加慢的问题,结合gzip压缩需求,以下是两种实用解决方案:

一、高效追加写入(推荐方案:JSON Lines + Gzip)

gzip是流式压缩格式,无法直接定位已压缩内容中的明文位置,因此传统的seek修改JSON数组末尾的方式不适用。改用JSON Lines格式(每行一个独立JSON对象)可实现真正的高效追加,无需读取整个文件:

写入代码

import gzip
import json

def append_to_gzip_jsonl(file_path, data_dict):
    # 以文本追加模式打开gzip文件,指定编码避免乱码
    with gzip.open(file_path, 'at', encoding='utf-8') as f:
        json.dump(data_dict, f)
        f.write('\n')

# 示例调用
append_to_gzip_jsonl('records.jsonl.gz', {'user_id': 101, 'action': 'login'})
append_to_gzip_jsonl('records.jsonl.gz', {'user_id': 102, 'action': 'logout'})
  • 核心优势:每次仅写入新数据的压缩内容,速度不受文件体积影响,且gzip压缩率更高。
  • 文件格式:每行一个JSON对象,兼具JSON的结构化和文本文件的可追加性。

二、兼容JSON数组格式的写入(仅适合小文件)

如果必须保持顶层为JSON数组的格式,只能读取原有内容后修改重写(大文件下效率仍会下降):

import gzip
import json

def append_to_gzip_json_array(file_path, data_dict):
    try:
        # 读取已有压缩数组
        with gzip.open(file_path, 'rt', encoding='utf-8') as f:
            data_list = json.load(f)
        data_list.append(data_dict)
        # 重新写入压缩文件
        with gzip.open(file_path, 'wt', encoding='utf-8') as f:
            json.dump(data_list, f)
    except FileNotFoundError:
        # 文件不存在时初始化数组
        with gzip.open(file_path, 'wt', encoding='utf-8') as f:
            json.dump([data_dict], f)

三、读取为字典列表

1. 读取JSON Lines格式的gzip文件

逐行解析并转换为列表:

import gzip
import json

def read_gzip_jsonl_to_list(file_path):
    records = []
    with gzip.open(file_path, 'rt', encoding='utf-8') as f:
        for line in f:
            line = line.strip()
            if line:
                records.append(json.loads(line))
    return records

# 示例调用
all_records = read_gzip_jsonl_to_list('records.jsonl.gz')

2. 读取JSON数组格式的gzip文件

直接用json.load加载整个数组:

import gzip
import json

def read_gzip_json_array(file_path):
    with gzip.open(file_path, 'rt', encoding='utf-8') as f:
        return json.load(f)

总结

  • 大文件场景优先选JSON Lines + Gzip,彻底解决追加效率问题。
  • JSON数组格式仅适合小体量数据,大文件下无法避免重新加载压缩的开销。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 18:05:29