Structured parsing and limits
Parse first, validate the meaning
Structured parsing reads a known format into data objects. It is not the same as evaluating program code. A JSON order with quantity 2 is syntactically valid and can satisfy a business rule. Quantity 0 can be valid JSON but invalid for a purchase. The server must check format, type, permitted fields and business meaning before acting.
A small order contract
For this offline exercise accept UTF-8 bytes at most 128 bytes long, containing one JSON object with exactly the field quantity. The quantity must be an integer from 1 through 5. Reject booleans, strings, unknown fields, duplicate keys and invalid JSON. These are fictional bookstore constraints, not universal limits. A server should enforce request-size limits before buffering and parsing, not merely after allocation.
Reason about boundary cases
The JSON text {"quantity": 1} is accepted and so is {"quantity": 5}. Values 0 and 6 are outside the allowed range. The string "2" and the Boolean true are not integers for this contract. A JSON array is the wrong top-level type. A repeated key creates ambiguity; this contract rejects duplicates explicitly because parsers can otherwise handle them differently.
Limit parser work and errors
Use a data-only parser, not general code evaluation or unsafe object deserialization. Python json.loads parses JSON but does not enforce this schema or all production resource limits. Bound input size, nesting where supported, processing time and output size as appropriate; handle decoding errors with a generic client response and minimal safe logs. This small offline fixture is not a production request parser. Valid data still needs authorization, binding and context-safe rendering.
Practice: define acceptance tests
Create cases for both allowed endpoints, just outside each endpoint, wrong type, duplicate field, missing field and excess bytes. Include valid Persian text in a separate title field scenario to distinguish byte limits from character counts. Use the chapter lab to compare your expected results with a reviewed toy parser. Sources: OWASP Input Validation and Python json documentation.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Structured parsing and limits — knowledge check
Apply defensive data handling to a fictional bookstore.
Which quantity meets the example contract?
What does syntactically valid JSON establish?
When should a service enforce a request byte limit?
How should the toy contract handle repeated quantity keys?
What does a JSON parser not automatically enforce?