作者: Jerry Fan

如何处理大型 JSONL 文件 (1GB+)

高效处理 GB 级 JSONL 数据的策略与最佳实践

为什么大型 JSONL 文件需要特殊处理

将整个 JSONL 文件解析为 Python 字典或 JavaScript 对象,所需内存可能远大于文件在磁盘上的大小。额外开销取决于记录数量、字段名、字段值和运行时环境。请用有代表性的文件实测,不要假定内存用量是文件大小的固定倍数。

JSONL 相比普通 JSON 的关键优势在于它可以逐行处理。每一行都是一个独立的 JSON 文档,这意味着您永远不需要加载整个文件。这种流式处理能力使 JSONL 成为机器学习、日志分析和数据工程中处理大型数据集的首选格式。

流式读取策略

处理大型 JSONL 文件的基本方法是逐行读取,独立处理每条记录。以下是使用流行语言和工具的实现方式。

Python 文件迭代每次读取一行。内存用量取决于最大的一行以及处理代码保留的数据;单条特别大的记录仍可能耗尽内存。

Python
import json


def process_large_jsonl(filepath: str) -> int:
    """Process a large JSONL file line by line."""
    count = 0
    errors = 0
    
    with open(filepath, 'r', encoding='utf-8') as f:
        for line_num, line in enumerate(f, 1):
            line = line.strip()
            if not line:
                continue
            try:
                record = json.loads(line)
                # Process your record here
                count += 1
            except json.JSONDecodeError as e:
                errors += 1
                print(f'Line {line_num}: {e}')
    
    print(f'Processed {count} records, {errors} errors')
    return count

Node.js 的 readline 接口提供了使用流逐行处理文件的高效方式,即使是多 GB 的文件也能保持最小的内存使用量。

Node.js
import { createReadStream } from 'fs';
import { createInterface } from 'readline';


async function processLargeJsonl(filepath) {
  const rl = createInterface({
    input: createReadStream(filepath, 'utf-8'),
    crlfDelay: Infinity,
  });


  let count = 0;
  for await (const line of rl) {
    const trimmed = line.trim();
    if (!trimmed) continue;
    try {
      const record = JSON.parse(trimmed);
      // Process your record here
      count++;
    } catch (err) {
      console.error(`Parse error: ${err.message}`);
    }
  }
  console.log(`Processed ${count} records`);
}

Unix 命令行工具非常适合快速检查和处理大型 JSONL 文件,无需编写任何代码。

命令行工具
# Count lines in a JSONL file
wc -l data.jsonl


# View first 10 records
head -n 10 data.jsonl


# View last 5 records
tail -n 5 data.jsonl


# Pretty-print first record
head -n 1 data.jsonl | jq .


# Filter records with jq
jq -c 'select(.age > 30)' data.jsonl


# Extract specific fields
jq -c '{name, email}' data.jsonl

内存管理技巧

除了基本的逐行读取之外,以下技巧可以帮助您更高效地处理大型 JSONL 文件。

以 1,000-10,000 条为一批处理记录,以平衡内存使用和处理效率。这在写入数据库或调用 API 时特别有用。

批量处理
import json
from typing import Iterator


def read_jsonl_batches(
    filepath: str,
    batch_size: int = 5000
) -> Iterator[list]:
    batch = []
    with open(filepath, 'r') as f:
        for line in f:
            record = json.loads(line.strip())
            batch.append(record)
            if len(batch) >= batch_size:
                yield batch
                batch = []
    if batch:
        yield batch


# Usage
for batch in read_jsonl_batches('large.jsonl'):
    # Insert batch into database
    db.insert_many(batch)

在处理过程中监控内存使用情况,以便及早发现问题并调整批次大小。

内存监控
import json
import psutil
import os


def process_with_monitoring(filepath: str):
    process = psutil.Process(os.getpid())
    
    with open(filepath, 'r') as f:
        for i, line in enumerate(f):
            record = json.loads(line)
            # Process record
            
            if i % 100000 == 0:
                mem = process.memory_info().rss / 1024 / 1024
                print(f'Line {i:,}: {mem:.1f} MB')

分割大型 JSONL 文件

有时您需要将大型 JSONL 文件分割成小文件,用于并行处理、上传到有大小限制的服务,或在多台机器间分配工作。

使用 split -l 保持每一行完整。不要用 split -b 生成可独立使用的 JSONL 分片:按字节划定的分割位置可能截断一条 JSON 记录或一个 UTF-8 字符。下方命令会创建新的目录,如果该目录已存在则停止执行。

使用 split 命令
# Split into parts of 100,000 complete lines in a NEW directory
mkdir jsonl-parts &&
split -l 100000 data.jsonl jsonl-parts/chunk_ &&
for f in jsonl-parts/chunk_*; do
    [ -f "$f" ] || continue
    mv "$f" "$f.jsonl"
done

这个 Python 替代方案按行数拆分,并保留输入的原始字节,包括 UTF-8 字符和换行符。它会创建新的输出目录,并拒绝覆盖已有目录。请先验证输入:拆分不会修复无效记录。

Python 脚本
from pathlib import Path


def split_jsonl(input_path, output_dir="jsonl-parts", lines_per_file=100000):
    if lines_per_file < 1:
        raise ValueError("lines_per_file must be positive")
    directory = Path(output_dir)
    file_num = 0
    output = None
    with open(input_path, "rb") as source:
        directory.mkdir()  # Refuse to overwrite an existing directory
        try:
            for line_number, line in enumerate(source):
                if line_number % lines_per_file == 0:
                    if output is not None:
                        output.close()
                    file_num += 1
                    output = (directory / f"part_{file_num:04d}.jsonl").open("xb")
                output.write(line)
        finally:
            if output is not None:
                output.close()
    print(f"Split into {file_num} files")


split_jsonl("data.jsonl")

压缩策略

当记录中的字段名和值大量重复时,JSONL 通常能取得较好的压缩效果。节省的空间取决于数据集、压缩级别和编解码器;请用有代表性的样本测量压缩后的大小和处理时间。

Python 的 gzip 模块可以透明地处理压缩的 JSONL 文件。.gz 扩展名是工具自动识别的约定。

读写 Gzip 压缩的 JSONL
import gzip
import json


# Reading gzipped JSONL
with gzip.open('data.jsonl.gz', 'rt', encoding='utf-8') as f:
    for line in f:
        record = json.loads(line)
        # Process record


# Writing gzipped JSONL
with gzip.open('output.jsonl.gz', 'wt', encoding='utf-8') as f:
    for record in records:
        f.write(json.dumps(record) + '\n')

压缩比较

请根据兼容性和在您自己的数据上测得的性能选择编解码器。以下列出的是取舍因素,并非基准测试结果:

gzip:支持广泛,是交换压缩 JSONL 文件的实用选择。

zstd:提供可调的压缩级别;请在您的工作负载下与 gzip 比较文件大小和吞吐量。

lz4:以快速压缩和解压为设计目标;请用您的数据测量速度与文件大小之间的取舍。

不压缩:省去解压处理,但占用更多存储空间;适合需要直接按字节访问的场景。

在浏览器中处理大文件

jsonl.co 在您的浏览器中本地读取 JSONL 文件。查看器分块扫描文件,并使用虚拟滚动,避免一次渲染所有记录。您的文件内容不会被上传。

可处理的文件大小取决于浏览器内存、设备资源、记录大小和执行的操作。流式读取输入并不保证输出所需的内存有固定上限:例如,Excel 转换会收集各行数据并在内存中构建工作簿。请先尝试较小的样本,必要时拆分文件。

在线处理大型 JSONL 文件

使用浏览器查看器在本地检查 JSONL。处理更大的数据量时,请拆分文件或使用上方逐行处理的脚本。

常见问题

参考资料