← All Exercises
Stream and Filter JSON Lines
intermediatepython
Background
JSON Lines is append-friendly and streamable: each line is an independent document, so one bad record need not discard the whole batch.
Problem
Read JSON Lines text, ignore blank lines, keep records whose kind is purchase and whose numeric amount is at least minimum, and return (kept, malformed_count). Malformed JSON or non-object records increment the count and processing continues.
Input
JSONL text and a numeric minimum amount.
Output
A tuple of kept purchase dictionaries in input order and the number of malformed non-blank lines.
Sample tests
Sample 1
Input: {"kind":"purchase","amount":25}
{"kind":"view","amount":99}
{"kind":"purchase","amount":10}
not-json
minimum = 20Expected: ([{'kind': 'purchase', 'amount': 25}], 1)Sample 2
Input: {"kind":"purchase","amount":5}
{"kind":"purchase","amount":7}
minimum = 6Expected: ([{'kind': 'purchase', 'amount': 7}], 0)Your solution
Learning objective
Build tolerant streaming parsers that isolate bad records and keep valid data flowing.