question 199 CSV JSON & JSONL · hard
Validate a JSONL payment stream
A payment provider streams events as JSON Lines. Before booking them, separate the valid payments from the bad lines, and say what is wrong with each bad line so the provider can fix it.
Function
validate_payments(path)Line numberscount every line of the file from 1, including blank lines; blank lines are skipped without an error
Checks, in order1. valid JSON → else
"line N: invalid JSON"; 2. payment_id is text starting with PAY → else "line N: bad payment_id"; 3. amount is an int or float (not true/false) and not negative → else "line N: bad amount"; 4. status is captured, failed or refunded → else "line N: bad status"Rulesreport only the first failed check for a line
Returns
(valid, errors): the valid records as dictionaries in file order, and the error messages in file orderExamples
callvalidate_payments('payments.jsonl')returns([{'payment_id': 'PAY0000045', 'order_id': 'O100043', 'amount': 12.93, 'status': 'captured'}, {'payment_id': 'PAY0008990', 'order_id': 'O108024', 'amount': 57.34, 'status': 'failed'}, {'payment_id': 'PAY0001357', 'order_id': 'O101217', 'amount': 71, 'status': 'refunded'}], ['line 4: bad payment_id', 'line 5: bad amount', 'line 6: invalid JSON', 'line 7: bad status'])