대용량 JSONL 파일 처리 방법 (1GB 이상)
기가바이트 규모의 JSONL 데이터를 효율적으로 처리하기 위한 전략과 모범 사례
최종 업데이트: 2026년 2월
대용량 JSONL 파일에 특별한 처리가 필요한 이유
JSONL 파일이 수백 메가바이트를 넘어 커지면 전체를 메모리에 로드하는 것이 비실용적이 됩니다. 복잡한 중첩 객체가 있는 1GB JSONL 파일은 Python 딕셔너리나 JavaScript 객체로 파싱하면 3~5GB의 RAM을 소비할 수 있습니다. 이로 인해 애플리케이션이 충돌하거나 시스템이 멈출 수 있습니다.
일반 JSON 대비 JSONL의 핵심 장점은 줄 단위로 처리할 수 있다는 것입니다. 각 줄은 독립적인 JSON 문서이므로 전체 파일을 로드할 필요가 없습니다. 이 스트리밍 기능이 바로 JSONL이 머신러닝, 로그 분석, 데이터 엔지니어링에서 대용량 데이터셋의 선호 형식인 이유입니다.
스트림 읽기 전략
대용량 JSONL 파일을 처리하는 기본 접근 방식은 줄 단위로 읽고 각 레코드를 독립적으로 처리하는 것입니다. 인기 있는 언어와 도구에서의 구현 방법을 소개합니다.
Python의 파일 반복은 본질적으로 메모리 효율적입니다. for 루프는 디스크에서 한 번에 한 줄씩 읽어 파일 크기에 관계없이 메모리 사용량을 일정하게 유지합니다.
import jsondef process_large_jsonl(filepath: str) -> int:"""Process a large JSONL file line by line."""count = 0errors = 0with open(filepath, 'r', encoding='utf-8') as f:for line_num, line in enumerate(f, 1):line = line.strip()if not line:continuetry:record = json.loads(line)# Process your record herecount += 1except json.JSONDecodeError as e:errors += 1print(f'Line {line_num}: {e}')print(f'Processed {count} records, {errors} errors')return count
Node.js의 readline 인터페이스는 스트림을 사용하여 줄 단위로 파일을 효율적으로 처리하는 방법을 제공하며, 수 기가바이트 파일에서도 메모리 사용량을 최소로 유지합니다.
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 herecount++;} catch (err) {console.error(`Parse error: ${err.message}`);}}console.log(`Processed ${count} records`);}
Unix 커맨드라인 도구는 코드를 작성하지 않고도 대용량 JSONL 파일을 빠르게 검사하고 처리하는 데 완벽합니다.
# Count lines in a JSONL filewc -l data.jsonl# View first 10 recordshead -n 10 data.jsonl# View last 5 recordstail -n 5 data.jsonl# Pretty-print first recordhead -n 1 data.jsonl | jq .# Filter records with jqjq -c 'select(.age > 30)' data.jsonl# Extract specific fieldsjq -c {name, email} data.jsonl
메모리 관리 기법
기본 줄 단위 읽기 외에도, 이 기법들은 대용량 JSONL 파일을 더 효율적으로 처리하는 데 도움이 됩니다.
메모리 사용량과 처리 효율성의 균형을 맞추기 위해 1,000~10,000개 단위로 레코드를 배치 처리합니다. 데이터베이스에 쓰거나 API 호출을 할 때 특히 유용합니다.
import jsonfrom typing import Iteratordef 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 batchbatch = []if batch:yield batch# Usagefor batch in read_jsonl_batches('large.jsonl'):# Insert batch into databasedb.insert_many(batch)
처리 중 메모리 사용량을 모니터링하여 문제를 조기에 발견하고 배치 크기를 조정합니다.
import jsonimport psutilimport osdef 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 recordif i % 100000 == 0:mem = process.memory_info().rss / 1024 / 1024print(f'Line {i:,}: {mem:.1f} MB')
대용량 JSONL 파일 분할
병렬 처리, 크기 제한이 있는 서비스에 업로드, 또는 여러 머신에 작업을 분산하기 위해 대용량 JSONL 파일을 더 작은 조각으로 분할해야 할 때가 있습니다.
Unix split 명령어는 JSONL 파일을 분할하는 가장 빠른 방법입니다. 줄 단위로 직접 작동하므로 JSONL에 완벽합니다.
# Split into files of 100,000 lines eachsplit -l 100000 data.jsonl chunk_# Split into files of approximately 100MB eachsplit -b 100m data.jsonl chunk_# Add .jsonl extension to split filesfor f in chunk_*; do mv "$f" "$f.jsonl"; done
필드 값별 분할이나 균형 잡힌 출력 크기 보장 같은 분할 로직을 더 세밀하게 제어하려면 Python을 사용합니다.
import jsondef split_jsonl(input_path: str, lines_per_file: int = 100000):file_num = 0line_count = 0out_file = Nonewith 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 += 1out_file = open(f'part_{file_num:04d}.jsonl', 'w')out_file.write(line)line_count += 1if out_file:out_file.close()print(f'Split into {file_num} files')
압축 전략
JSONL 파일은 JSON 텍스트의 높은 중복성 때문에 매우 잘 압축됩니다. 압축은 파일 크기를 70~90% 줄여 스토리지를 절약하고 전송 속도를 높일 수 있습니다.
Python의 gzip 모듈은 압축된 JSONL 파일을 투명하게 처리합니다. .gz 확장자는 도구가 자동으로 인식하는 관례입니다.
import gzipimport json# Reading gzipped JSONLwith gzip.open('data.jsonl.gz', 'rt', encoding='utf-8') as f:for line in f:record = json.loads(line)# Process record# Writing gzipped JSONLwith 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% 프라이빗.