How to Stream a Large JSONL File Line by Line in Python

Process a large JSON-lines file incrementally using streaming techniques to avoid loading the entire file into memory.

Medium Python 3.9+ Aug 9, 2026 Data pipelines & processing 13 views 0 copies

Python code

42 lines
Python 3.9+
import json

def process_large_file(filepath, chunk_size=8192):
    """
    Stream a large JSON-lines file line by line, processing each record
    without loading the entire file into memory.
    """
    total_count = 0
    total_sum = 0
    
    with open(filepath, 'r') as f:
        while True:
            chunk = f.readlines(chunk_size)
            if not chunk:
                break
            for line in chunk:
                line = line.strip()
                if not line:
                    continue
                record = json.loads(line)
                total_count += 1
                total_sum += record.get('value', 0)
    
    return total_count, total_sum

if __name__ == "__main__":
    # Simulate a large file with a generator to demonstrate streaming
    import tempfile
    import os
    
    # Create a sample large file (1000 records)
    with tempfile.NamedTemporaryFile(mode='w', suffix='.jsonl', delete=False) as f:
        for i in range(1000):
            f.write(json.dumps({"id": i, "value": i * 2}) + "\n")
        filepath = f.name
    
    # Process it in streaming fashion
    count, total = process_large_file(filepath)
    print(f"Processed {count} records, total sum: {total}")
    
    # Clean up
    os.unlink(filepath)

Output

stdout
Processed 1000 records, total sum: 999000

How it works

The function uses readlines(chunk_size) to read a fixed number of lines per chunk, balancing memory usage and I/O efficiency. Each line is parsed with json.loads and processed immediately, so only one record stays in memory at a time. The strip() call removes trailing newlines, and empty lines are skipped to avoid parsing errors. This pattern is ideal for files too large to fit in RAM, as it processes records incrementally.

Common mistakes

  • Using `read()` or `readlines()` without size, which loads the whole file into memory
  • Forgetting to strip newline characters before JSON parsing
  • Assuming all lines are valid JSON; add error handling for corrupted records

Variations

  1. Use `for line in file:` to iterate directly — simplest, though chunking gives more control over I/O sizes
  2. Process with a generator that yields each parsed record for downstream pipeline stages

Real-world use cases

  • Aggregating metrics from a multi-gigabyte server access log in JSONL format
  • Feeding millions of event records into a stream processor like Kafka or a database batch insert
  • Filtering and enriching large exported datasets before loading into a data warehouse

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Data pipelines & processing

Related tutorials and quizzes for this topic.