Product case study · November 30, 2026
Ask Claude Code to stop a JSONL import losing records
Repair a Python JSONL reader that skips damaged records. Give Claude Code fixed tests for blank lines, truncated input and useful line-number errors.

A completed import is not proof that every record survived. Reject broken lines before returning a batch, and report where parsing stopped.
Your export contains three job records. The importer returns two and reports no error. A damaged middle line vanished because the reader caught the parsing exception and continued.
This exercise gives Claude Code a repair with a measurable result: either return the complete parsed batch or raise an error naming the first broken line. You will also protect a valid final record that has no newline after it. Missing punctuation inside a record and a missing final line terminator are different conditions.
You need Bash, Python 3, and an installed, signed-in Claude Code. The Python baseline and reference repair below were tested locally. The agent prompt is an authored exercise, not a recorded Claude Code run. Sources were checked November 30, 2026.
Reproduce the missing job
Create a disposable folder and save this deliberately broken reader:
jsonl_lab=$(mktemp -d /tmp/claude-jsonl-records.XXXXXX)
cd "$jsonl_lab"
cat > reader.py <<'PY'
import io
import json
def load_records(text):
records = []
for line in io.StringIO(text):
try:
records.append(json.loads(line))
except json.JSONDecodeError:
continue
return records
PY
python3 - <<'PY'
from reader import load_records
text = '{"job":1}\n{"job":\n{"job":3}\n'
print(load_records(text))
PY
The baseline prints:
[{'job': 1}, {'job': 3}]
The reader has no evidence that job 2 was unimportant. It silently made that decision through continue. In an import used to count completed work, the resulting list can look perfectly ordinary.
The JSON Lines format specifies one valid JSON value per line, UTF-8 encoding and no byte order mark. A blank line is not a value, while null is. A newline after the final value is recommended but optional. Those rules explain why deleting the last line whenever a file lacks a final newline would lose legitimate data.
This lab begins with an already decoded Python string. When connecting it to a completed file, decode with UTF-8 and strict errors; do not discard undecodable bytes. Work from a stable copy of an export rather than a file another process is still appending to.
Freeze the acceptance criteria
Save this as SPEC.md:
load_records(text) receives a complete, decoded JSONL document as a string.
Return a list containing every parsed value in order, or raise ValueError.
An empty document returns an empty list.
A blank line, malformed middle record or truncated final record must fail.
The error must start with "Invalid JSON on line N:" using physical line
numbers starting at 1. Preserve the original parser exception as the cause.
Accept a complete final value without a trailing newline and CRLF endings.
Preserve escaped newlines and Unicode inside strings.
Accept JSON scalar values as well as objects and arrays.
Change only reader.py; keep this specification and the tests unchanged.
Use the standard library. Do not write files or perform import side effects.
Save the following as test_reader.py:
import json
import unittest
from reader import load_records
class ReaderTests(unittest.TestCase):
def assert_bad_line(self, text, number):
with self.assertRaises(ValueError) as caught:
load_records(text)
self.assertTrue(str(caught.exception).startswith(
f"Invalid JSON on line {number}:"))
self.assertIsInstance(caught.exception.__cause__, json.JSONDecodeError)
def test_objects_and_crlf(self):
text = '{"job":1}\r\n{"city":"香港"}\r\n'
self.assertEqual(load_records(text), [{"job": 1}, {"city": "香港"}])
def test_complete_final_record_without_newline(self):
self.assertEqual(load_records('{"job":1}\n{"job":2}'),
[{"job": 1}, {"job": 2}])
def test_empty_document(self):
self.assertEqual(load_records(""), [])
def test_blank_line_is_not_a_record(self):
self.assert_bad_line('{"job":1}\n \n{"job":3}\n', 2)
def test_malformed_middle_record(self):
self.assert_bad_line('{"job":1}\n{"job":\n{"job":3}\n', 2)
def test_truncated_final_record(self):
self.assert_bad_line('{"job":1}\n{"job":', 2)
def test_string_contents_are_preserved(self):
value = {"note": "first\nsecond", "separator": "a\u2028b"}
text = json.dumps(value, ensure_ascii=False) + "\n"
self.assertEqual(load_records(text), [value])
def test_scalar_and_array_values(self):
self.assertEqual(load_records('null\nfalse\n0\n""\n[]\n'),
[None, False, 0, "", []])
Run the fixed checks:
python3 -m unittest -v test_reader
Locally, the broken reader passed five tests and failed three: blank line, malformed middle record and truncated final record. Each failure exposed an error that the reader had swallowed.
The Unicode separator in the string test is deliberate. It protects against a patch that uses str.splitlines() and splits a valid string at a Unicode line separator. This format uses the newline character as its record boundary; text that looks like a line break on screen is not necessarily a new record. Python documents the broader boundaries recognized by str.splitlines().
Give Claude the failing command
Start claude inside the practice folder and paste:
Read SPEC.md, reader.py and test_reader.py.
Run python3 -m unittest -v test_reader and report the baseline.
Explain how the current reader can return an incomplete batch as success.
Change only reader.py to meet the specification and existing tests.
Do not skip invalid lines, return a partial list, delete a final record,
edit tests, install packages, commit, delegate or access other folders.
Keep the original JSON parsing exception as the cause of the line error.
Rerun the same command and report its actual output.
Explain the difference between malformed JSON and a missing final newline.
Anthropic’s debugging workflow recommends giving Claude reproduction steps and checking the repair. Here the failing command and immutable tests make “fixed” something you can verify. Review the proposed tool actions under your configured permissions; a prompt’s folder boundary does not provide process isolation.
Review the repair before accepting it
This reference implementation passed all eight tests locally:
import io
import json
def load_records(text):
records = []
for number, line in enumerate(io.StringIO(text), start=1):
try:
value = json.loads(line)
except json.JSONDecodeError as exc:
raise ValueError(
f"Invalid JSON on line {number}: {exc.msg}"
) from exc
records.append(value)
return records
Python’s json.loads() and JSONDecodeError provide the parsing and error details. The wrapper adds the document’s physical line number because each parser call sees only one line. raise ... from exc keeps the underlying exception available for diagnosis.
The function collects values internally but returns only after all lines parse. On failure, its caller receives an exception instead of a partial list. That property would change if you replaced return with a generator yielding each record. A downstream consumer could already have acted on earlier values before the generator reached the broken line.
No special check for a trailing newline is necessary. A complete final value still parses; incomplete JSON fails. The reference also preserves false-like values such as null, false, zero and an empty string. A filter like if value would silently throw those records away.
Recover the data without hiding the error
After the agent finishes, run the tests yourself. If they unexpectedly passed before any patch, check which file Python imported:
python3 -c 'import reader; print(reader.__file__)'
If only the line-number checks fail, look for an error reporting the parser’s local line 1 instead of the enclosing document line. If the Unicode case fails, inspect the line-splitting method. If any tests were edited, restore the original checks before judging the patch.
For a damaged real export, retain the original and inspect the reported line. Re-export from the source when possible. Do not invent the missing value or automatically remove a truncated record to get a green result. If a business process permits partial recovery, make that a separate operation with rejected-line evidence and an explicit partial status.
This reader is for small completed batches: it holds the input string and result list in memory. It provides no database transaction or rollback for writes performed elsewhere. Larger imports need staging and their own commit policy. It also retains Python’s default handling of duplicate object keys and non-finite numbers; it is not a complete strict-JSON conformance validator. For those separate contracts, see the duplicate-key exercise and finite-number validation exercise.
The acceptance rule for this repair is narrow and useful: a syntactically broken record cannot quietly disappear from a successful returned batch.
Sources
Checked November 30, 2026:
- JSON Lines: format documentation — record boundaries, valid values, encoding and final newline rules.
- Python: json — parsing, exception details and default decoder behavior.
- Python: str.splitlines — recognized line boundaries beyond newline.
- Anthropic: Common workflows — reproducing bugs and verifying code changes.
Put this to work
How an exception handler can turn a parsing error into silent data loss.
Try
Ask Claude Code to repair a small JSONL reader without changing its fixed tests.
Prove it worked
Run eight tests against the broken reader and the reference repair.
Keep in view
- Reproduce an importer that reports success after dropping a damaged row.
- Keep valid final records even when the file has no trailing newline.
- Require a physical line number when a batch cannot be parsed.