Back to section lessons
18 min · easy · Lesson 3 of 8

JSONL: reading data one line at a time

Learn the JSONL format and read the course corpus with a line length limit and precise error messages.

Lesson contents
  1. 1 Why JSONL works well for a dataset
  2. 2 Strict rules
  3. 3 Errors should identify the location
  4. 4 Limiting line length
  5. 5 Duplicate records
  6. 6 Task
  7. 7 Common mistake

Why JSONL works well for a dataset

Each line in JSONL contains a complete JSON value. The course file looks like this:

{"id":"inc-001-a","source_id":"inc-001","text":"API не отвечает","label":"availability"}
{"id":"inc-002-a","source_id":"inc-002","text":"DNS не находит имя","label":"connectivity"}

You can process the file line by line without keeping the whole file in memory. This helps both on a modest computer and when working with a large corpus.

Strict rules

The course file uses UTF-8 encoding without a BOM. Encoding determines how characters are written as bytes; a BOM is a special marker at the start of a file. Blank lines are forbidden. Each line must contain one JSON object, and a trailing newline is allowed.

json.loads turns text containing a JSON object into a Python dictionary. NaN and Infinity represent a not-a-number value and infinity; strict JSON forbids them. Use parse_constant to provide a function that stops parsing when it encounters one:

import json

line = (
    '{"id":"inc-001-a","source_id":"inc-001",'
    '"text":"API не отвечает","label":"availability"}'
)

def reject_constant(value: str):
    raise ValueError(f"non-finite number: {value}")

record = json.loads(line, parse_constant=reject_constant)
print(record["label"])  # availability

By default, json.loads accepts these values as a Python extension, even though they are not part of strict JSON. For a dataset, it's better to fail validation.

Errors should identify the location

invalid JSON doesn't tell you where to look. The reader knows the file path and line number, so it can include both:

data/incidents.jsonl:17: invalid JSON

Line numbering starts at one. Schema errors, blank lines, duplicate id values and overly long lines use the same format.

Limiting line length

One corrupted line can occupy hundreds of megabytes. The reader should set an upper limit and reject the line before passing it to the JSON parser.

Run the following example from the course project folder. It reads the project's data/incidents.jsonl file. Path stores a file path, with closes the file after reading, and enumerate(..., start=1) adds a line number:

from pathlib import Path

path = Path("data/incidents.jsonl")
with path.open("r", encoding="utf-8") as stream:
    for line_number, line in enumerate(stream, start=1):
        print(line_number, line.strip())

This loop doesn't load the whole file at once, but it still reads each line in full. The project's reader therefore uses readline(max_line_bytes + 1) and checks the number of bytes read before parsing JSON.

Don't use read() or readlines(): both load the entire contents into memory.

Duplicate records

The id field is unique across the file. A set stores only distinct values. Use in to look for an identifier and add to insert a new one:

records = [{"id": "inc-001-a"}, {"id": "inc-002-a"}]
seen_ids: set[str] = set()

for record in records:
    if record["id"] in seen_ids:
        raise ValueError("duplicate id")
    seen_ids.add(record["id"])

print(len(seen_ids))  # 2

A repeated source_id is allowed. It identifies different wordings of the same incident and will be used for a group split.

Task

Implement this function in exercises/lesson03.py:

def read_records(path) -> list:
    ...

The streaming validator is called iter_jsonl and lives in incident_classifier.data. The read_jsonl wrapper collects its output into a list: the small course corpus is needed in full for splitting and training. The line length limit applies while reading, but the total list size depends on the corpus. Import the wrapper and call it inside your function. This exercise lets you understand the reader's contract first and use the same tested code in later tasks.

Required failures:

The provided reader handles these checks. Every error message includes the file path and line number.

Hints

Open src/incident_classifier/data.py and find read_jsonl. It already accepts Path | str and returns a list of validated records.

Don't copy the reader implementation into your exercise file. Importing it keeps the same validation order for the CLI, training and tests.

Check

python -m pytest -q tests/test_exercises.py --student exercises -k lesson03

The CLI also validates the entire dataset:

python -m incident_classifier validate data/incidents.jsonl
Where to find the solution

The reference wrapper is in solutions/lesson03.py. The reader itself is in src/incident_classifier/data.py. Read its validation order once your exercise test passes.

python -m pytest -q tests/test_exercises.py --student solutions -k lesson03

Common mistake

json.loads(path.read_text()) expects one JSON document and loads the entire file. Parse JSONL one line at a time instead.

Done reading?

Mark the lesson as read to move your track progress forward.

Practice

Fix a local lab. The agent checks your work and gives hints if you get stuck.

Full access to all labs

$134 $67.00 for one year −50%

One payment, no auto-renewal · Terms

Buy for $67.00