如何處理大型 JSONL 檔案(1GB 以上)

高效處理 GB 級 JSONL 資料的策略與最佳實踐

最後更新:2026 年 2 月

為什麼大型 JSONL 檔案需要特殊處理

當 JSONL 檔案增長到數百 MB 以上時,將其完全載入記憶體就變得不切實際了。一個包含複雜巢狀物件的 1GB JSONL 檔案在解析為 Python 字典或 JavaScript 物件後可能會消耗 3-5GB 的 RAM。這可能導致應用程式崩潰或使系統完全停頓。

JSONL 相對於一般 JSON 的關鍵優勢在於它可以逐行處理。每一行都是一個獨立的 JSON 文件,這意味著您永遠不需要載入整個檔案。這種串流處理能力使 JSONL 成為機器學習、日誌分析和資料工程中大型資料集的首選格式。

串流讀取策略

處理大型 JSONL 檔案的基本方法是逐行讀取,獨立處理每筆記錄。以下是流行語言和工具的實現方式。

Python 的檔案迭代天生就具有記憶體效率。for 迴圈每次只從磁碟讀取一行,無論檔案大小如何,記憶體使用量都保持恆定。

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 檔案分割成較小的片段,以進行平行處理、上傳到有大小限制的服務,或在不同機器之間分配工作。

Unix 的 split 命令是分割 JSONL 檔案最快的方式。它直接按行操作,非常適合 JSONL。

使用 split 命令
# Split into files of 100,000 lines each
split -l 100000 data.jsonl chunk_
# Split into files of approximately 100MB each
split -b 100m data.jsonl chunk_
# Add .jsonl extension to split files
for f in chunk_*; do mv "$f" "$f.jsonl"; done

若需要更精確地控制分割邏輯,例如按欄位值分割或確保輸出大小均衡。

Python 腳本
import json
def split_jsonl(input_path: str, lines_per_file: int = 100000):
file_num = 0
line_count = 0
out_file = None
with open(input_path, 'r') as f:
for line in f:
if line_count % lines_per_file == 0:
if out_file:
out_file.close()
file_num += 1
out_file = open(f'part_{file_num:04d}.jsonl', 'w')
out_file.write(line)
line_count += 1
if out_file:
out_file.close()
print(f'Split into {file_num} files')

壓縮策略

JSONL 檔案的壓縮效果非常好,因為 JSON 文字具有高度的重複性。壓縮可以將檔案大小減少 70-90%,節省儲存空間並加速傳輸。

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')

壓縮比較

1GB 混合資料 JSONL 檔案的典型壓縮率:

gzip:減少 70-80%(1GB 壓縮至 200-300MB),廣泛支援

zstd:減少 75-85%(1GB 壓縮至 150-250MB),解壓縮更快

lz4:減少 60-70%(1GB 壓縮至 300-400MB),速度最快

不壓縮:存取速度最快,最適合頻繁隨機讀取

在瀏覽器中處理大型檔案

jsonl.co 專門設計用於直接在瀏覽器中處理 1GB 以上的 JSONL 檔案。它使用串流處理和 Web Workers 在本機處理檔案,無需將檔案上傳到任何伺服器。

這意味著您的資料保持私密,而且無需等待上傳即可獲得即時結果。檢視器可以使用虛擬捲動顯示數百萬筆記錄,所有轉換工具都支援串流處理大型檔案。

試試我們的免費 JSONL 工具

直接在瀏覽器中檢視、驗證和轉換大型 JSONL 檔案。無需上傳、無檔案大小限制、100% 私密。

線上處理大型 JSONL 檔案

直接在瀏覽器中檢視、驗證和轉換高達 1GB 的 JSONL 檔案。無需上傳,100% 私密。

常見問題

大型 JSONL 檔案(1GB+)— 串流、拆分、壓縮 | jsonl.co