Review Robustness and Data Trust
Core idea
Validate input before aggregation. Read a bounded number of bytes, decode strictly as UTF-8, reject repeated object keys using object_pairs_hook, then check exact fields, ID format, category, amount type and range, row count and unique IDs. JSON syntax alone does not prove a valid order. Reject malformed UTF-8, malformed JSON, excessive nesting detected by the parser, nonstandard numeric constants and contract violations. The CLI maps expected input failures to the fixed message “invalid input”; it never echoes the offending record. Size limits reduce risk but do not prove safety for arbitrary hostile workloads.
from io import BytesIOdef read_bounded(stream, limit): data = stream.read(limit + 1) if len(data) > limit: raise ValueError('too large') return datafor data in (b'1234', b'12345'): try: print(len(read_bounded(BytesIO(data), 4))) except ValueError: print('rejected')Reading only the limit would silently accept a truncated prefix. One extra byte detects overflow for this blocking stream.
Expected output:
4rejectedReject duplicate object keys
import jsondef unique_pairs(pairs): result = {} for key, value in pairs: if key in result: raise ValueError('duplicate key') result[key] = value return resulttry: json.loads('{"amount_cents": 1, "amount_cents": 2}', object_pairs_hook=unique_pairs)except ValueError: print('rejected')The hook receives pairs before a normal dictionary could hide the first duplicate.
Expected output:
rejectedCommon mistake
Do not silently coerce values with int(value); it can accept values outside the intended contract. Do not log raw input or expose tracebacks for predictable invalid data. Unexpected I/O failures have a separate operational path in the full CLI.
Practice
Run the project tests for repeated keys, duplicate IDs, Boolean values, malformed UTF-8, oversize data and invalid category. Add one extra-field case; verify no partial report is printed.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Robustness and security review
Check your understanding of robustness and security review.
What is printed?
import jsonprint(json.loads('{"a":1,"a":2}')['a'])What is printed?
print(type(1.0) is int, type(1) is int)Why read limit plus one?
Which error output respects privacy?