如何處理大型 JSONL 檔案(1GB 以上)
高效處理 GB 級 JSONL 資料的策略與最佳實踐
為什麼大型 JSONL 檔案需要特殊處理
將整個 JSONL 檔案解析為 Python 字典或 JavaScript 物件,所需記憶體可能遠大於檔案在磁碟上的大小。額外開銷取決於記錄數量、欄位名稱、欄位值和執行環境。請用具代表性的檔案實測,不要假定記憶體用量是檔案大小的固定倍數。
JSONL 相對於一般 JSON 的關鍵優勢在於它可以逐行處理。每一行都是一個獨立的 JSON 文件,這意味著您永遠不需要載入整個檔案。這種串流處理能力使 JSONL 成為機器學習、日誌分析和資料工程中大型資料集的首選格式。
串流讀取策略
處理大型 JSONL 檔案的基本方法是逐行讀取,獨立處理每筆記錄。以下是流行語言和工具的實現方式。
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 countNode.js 的 readline 介面提供了一種使用串流逐行處理檔案的高效方式,即使是數 GB 的檔案也能保持最低的記憶體使用量。
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 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 字元和換行字元。它會建立新的輸出目錄,並拒絕覆寫已有目錄。請先驗證輸入:分割不會修復無效記錄。
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 副檔名是一種工具會自動識別的慣例。
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。檔案內容留在您的裝置上;可處理的資料量和處理時間取決於瀏覽器及所選工具。
按行數將大型 JSONL 檔案拆分為更小、更易管理的檔案區塊。
將多個 JSONL 檔案合併為一個,支援去重。
比較 gzip、zstd 和 Brotli 壓縮 JSONL 檔案的效果。包含基準測試、Python 和 Node.js 程式碼範例、雲端儲存策略和最佳實踐。
逐行驗證 JSONL 檔案。即時捕獲語法錯誤、編碼問題和格式問題。
直接在編輯器裡把 .jsonl 和 .ndjson 開成一張快速、可搜尋的表格。為大到捲不動的檔案,以及還在持續寫入的日誌而做。