Module: L1-M05 · Duration: ~165 min (estimate, including the independent exercise) · Previous: L1-M04-L05 · Next: L02 - Structured-output features and validation in code
1. Introduction
When an LLM feature returns data for other code to use, for example a ticket classification, extracted information or the arguments for calling a function, the output is usually JSON. From that point on, the model's answer is no longer just for a person to read. It goes into the system: it is stored in a database, used to choose a queue, used to call another API.
OWASP advises: "Treat the model as any other user, adopting a zero-trust approach, and apply proper input
validation on responses coming from the model to backend functions" [R1]. The standard tool for describing "what
valid JSON looks like" is JSON Schema. This lesson teaches you to read, write and test a schema, with the
Python library jsonschema.
2. Learning objectives
- Explain the structure of JSON and one important ambiguity: duplicate names in an object.
- Read and write JSON Schema with
type,properties,required,additionalProperties,enum,minimum/maximum,minLength/maxLength,pattern,anyOf. - Run validation with
jsonschemaand read every error, including the path to the wrong spot. - Verify a schema with valid samples and invalid samples, each invalid sample breaking exactly one rule.
- Recognise the cases that are easy to miss:
2.0is an integer,formatis not checked by default, a misspelled keyword is ignored.
3. Prerequisites and tools
- L1-M04-L01: oracles. A schema is a rule oracle for the structure of the output.
- L1-M03: pytest, fixtures,
parametrize. - The code lab
code-labs/l1-m05, installed as described in the lab's README. No API key is needed.
4. Concepts
4.1 JSON on one page
JSON (RFC 8259) has these values: object {"tên": giá_trị} (name: value), array [...], string "...", number,
true/false and null. An example ticket:
{"category": "refund", "priority": 3, "order_id": "SE1003", "summary": "Khách muốn trả hàng", "needs_human": false}
In English: the summary reads "The customer wants to return an item".
One ambiguity a tester needs to know: RFC 8259 says "The names within an object SHOULD be unique", and if a name is duplicated, "the behavior of software that receives such an object is unpredictable. Many implementations report the last name/value pair only. Other implementations report an error or fail to parse the object" [R2]. Python keeps the last pair. So validate the parsed value, because that is the value your code will use.
Everyday example. A parcel form is misprinted with two "Recipient phone" boxes, and the customer writes two different numbers. Courier A calls the number in the last box; courier B sends the form back because he cannot tell which number is right. One form, two ways of handling it, exactly as RFC 8259 describes. Python is courier A, so a tester checks the number the "courier" will really call: the parsed value.
4.2 JSON Schema: describing "valid" in JSON
JSON Schema is a JSON document that describes which JSON documents are accepted. This module uses version Draft 2020-12 [R3]. The main keywords:
| Keyword | Meaning | Example in the ticket |
|---|---|---|
type |
Data type. The spec: "integer" matches "any number with a zero fractional part" [R4] | "priority": {"type": "integer"} |
properties |
A schema for each field | |
required |
Valid when "every item in the array is the name of a property in the instance" [R4] | all 5 fields |
additionalProperties: false |
No field outside properties is allowed |
blocks "extra": true |
enum |
Valid when the value "is equal to one of the elements in this keyword's array value" [R4] | category |
minimum, maximum |
Inclusive bounds: valid when greater than "or exactly equal to" minimum [R4] |
priority 1-5 |
minLength, maxLength |
String length | summary 1-200 |
pattern |
A regular expression | order_id: ^SE[0-9]{4}$ |
anyOf |
Matches at least one of the schemas | order_id is a string or null |
items, minItems, maxItems |
A schema for each element of an array; the minimum and maximum number of elements | {"type": "array", "minItems": 1, "maxItems": 5, "items": {"type": "object", ...}} |
The full schema is in lab/schemas.py (TICKET_SCHEMA).
Everyday example. A bank's account-opening form: boxes marked * are mandatory (required), the
"Account type" box takes exactly one of the printed choices (enum), "Date of birth" has exactly 8
little squares (pattern), and the clerk refuses a form with extra notes written in the margin
(additionalProperties: false). A JSON Schema is that form, written in JSON.
Worked example: reading an anyOf. order_id is valid when it matches at least one branch: a
string following ^SE[0-9]{4}$, or null. Run in the lab folder, with the venv activated:
python -c "from lab.schemas import validate; from lab.demo import GOOD; print(validate({**GOOD, 'order_id': None})); print(validate({**GOOD, 'order_id': 'SE10031'}))"
[]
["$.order_id: 'SE10031' is not valid under any of the given schemas"]
| Value | Branch 1: string ^SE[0-9]{4}$ |
Branch 2: null |
Result |
|---|---|---|---|
None |
no (not a string) | matches | valid |
"SE10031" |
no (5 digits, and $ requires the string to end right after 4 digits) |
no | anyOf error |
Output run on 2026-11-06 on Python 3.14.6 and 3.12.3, Linux, identical on both versions; so is every other output in this lesson.
4.3 Validating like a tester
Three principles:
- Report every error, not just the first one. When an output is wrong in three places, whoever fixes it needs to know all three.
- Report the path to the wrong spot.
$.priorityis much easier to read than "invalid data". - Test the schema itself. A schema is an oracle (L1-M04-L01). A schema can be too loose (letting wrong output through) or written so wrongly that everything passes.
Good vs bad: a test for a schema. Same goal, "the schema catches wrong output":
# Weak: one sample wrong in three places; only asserts "there is an error"
def test_bad_ticket_fails():
assert validate({**GOOD, "priority": 9, "category": "Refund", "summary": ""}) != []
# Good: each sample wrong in exactly one place; assert one error and its keyword
@pytest.mark.parametrize("change,words", [
({"priority": 9}, "maximum of 5"),
({"category": "Refund"}, "is not one of"),
({"summary": ""}, "should be non-empty"),
])
def test_each_rule_is_enforced(change, words):
errors = validate({**GOOD, **change})
assert len(errors) == 1 and words in errors[0], errors
If someone
removes maximum and enum from the schema, the weak test stays green, because minLength still
catches the empty summary. The good test fails at once, on the case of the rule that was lost.
4.4 The cases that are easy to miss
| Case | What happens | Why it matters |
|---|---|---|
"priority": 2.0 |
Valid with "type": "integer" (a number whose fractional part is 0) |
Code that uses priority as a list index can still break |
"priority": true |
Invalid. jsonschema does not treat a boolean as a number, even though True == 1 in Python |
|
"format": "email" |
Not checked by default: "By default, as per the specification, no validation is enforced" [R5] | You must enable FormatChecker if you want it checked |
A schema with a wrong value, for example "required": "order_id" (a string instead of an array) or "type": "objekt" |
The validator behaves unpredictably: with required as a string, it treats each character as a required field and rejects every valid instance ("'o' is a required property"); with objekt, it raises UnknownType. The lab's validate() calls check_schema() first, so both raise a clear SchemaError |
An error in the schema must be reported as an error in the schema, not mixed up with an error in the output |
A misspelled keyword, for example "propertiez" |
An unknown keyword is ignored, even by check_schema(). Every instance is valid |
Only invalid samples can catch it: this is why you must test the schema itself |
An error inside anyOf |
The message only says "is not valid under any of the given schemas", not which branch is wrong | State in the bug report which value was sent |
Worked example: three values of priority, and an email.
python -c "from lab.schemas import validate; from lab.demo import GOOD; print(validate({**GOOD, 'priority': True})); print(validate({**GOOD, 'priority': 2.0})); print(validate({**GOOD, 'priority': 2.5}))"
python -c "from lab.schemas import validate; s = {'type': 'string', 'format': 'email'}; print(validate('không có', s)); print(validate('không có', s, check_formats=True))"
["$.priority: True is not of type 'integer'"]
[]
["$.priority: 2.5 is not of type 'integer'"]
[]
["$: 'không có' is not a 'email'"]
2.0 passes because its fractional part is 0, and 2.5 does not. True is blocked although
True == 1 in Python. The string "không có" ("none") is only caught with check_formats=True:
exactly situation 2 in section 7.
5. Technical deep dive
5.1 lab/schemas.py
validator = Draft202012Validator(schema, format_checker=FormatChecker() if check_formats else None)
errors = sorted(validator.iter_errors(instance), key=...)
return [f"{e.json_path}: {e.message}" for e in errors]
iter_errors"Lazily yield[s] each of the validation errors in the given instance" [R5], so you get every error.e.json_pathis "A JSON path to the offending element within the instance" [R5], for example$.priority.e.messageis the message for a human reader;e.validatoris the keyword that failed, for examplemaximum.- The results are sorted by path, so the output is stable between runs.
Worked example: e.validator, and why sorting matters. Loop straight over iter_errors with the
demo's bad ticket and print the path and the keyword that failed:
python -c "from jsonschema import Draft202012Validator; from lab.schemas import TICKET_SCHEMA; bad = {'category': 'Refund', 'priority': 9, 'order_id': 'se1003', 'summary': '', 'extra': True}; [print(e.json_path, e.validator) for e in Draft202012Validator(TICKET_SCHEMA).iter_errors(bad)]"
$.category enum
$.priority maximum
$.order_id anyOf
$.summary minLength
$ required
$ additionalProperties
Still all 6 errors of the demo in section 8.1, but in the order the validator walks the schema, not by
path. validate() sorts them, so two runs always give the same list and a diff in CI is easy to read.
The second column says which keyword caught the error: the empty summary is caught by minLength,
even though the message says "should be non-empty".
5.2 The Python you need for this lesson
json.loads(text)turns a JSON string into a dict/list;json.dumps(obj)does the reverse.{**GOOD, "priority": 0}creates a new dict: it copiesGOODand then replaces one field. The tests in this lesson use it to build "wrong in exactly one place" samples without changing the original sample.del d["key"]removes a field from a dict.
Good vs bad: copying a sample with nested objects. {**GOOD, ...} copies only the outermost
level. For the ticket (every field a single value) that is enough; for a sample with an items
array, like the exercise in section 9, it is not:
python -c "a = {'id': 'SE1003', 'items': [{'sku': 'A1', 'quantity': 1}]}; b = {**a}; b['items'][0]['quantity'] = 0; print(a['items'][0]['quantity'])"
python -c "import copy; a = {'id': 'SE1003', 'items': [{'sku': 'A1', 'quantity': 1}]}; b = copy.deepcopy(a); b['items'][0]['quantity'] = 0; print(a['items'][0]['quantity'], b['items'][0]['quantity'])"
0
1 0
First command (bad): changing the copy also breaks the original a, so every sample made after it is
wrong in one more, unintended place. Second command (good): copy.deepcopy copies the inner levels
too, and the original stays intact. Extra exercise 9.1 practises exactly this.
6. The QA perspective
- What to test: every keyword of the schema has at least one violating sample; every bound has a value on the
bound and a value outside it; a missing required field; an extra field;
nullwhere it is allowed and where it is not. - Each invalid sample breaks exactly one rule. A sample that is wrong in three places only tells you "there is an error", not whether the schema catches each error.
- What can go wrong: a schema that is too loose (missing
additionalProperties: false, missingrequired); a schema that is too strict (rejecting valid output); wrong expectations aboutintegerandformat. - How to report: attach the real JSON (with sensitive data masked) and the list of errors with their paths.
7. Real-world scenarios
Scenario 1 (fictional): an extra field. A model that extracts invoice information sometimes adds the field
"discount_note". The schema has no additionalProperties: false, so the output is still "valid". The code behind
it stores the whole object in the database, and an old report breaks because it meets an unexpected column. The
lesson: by default, do not accept extra fields unless the requirement says otherwise.
Scenario 2 (fictional): a "valid" email. The team believes that "format": "email" checks the email. In fact
the validator does not check formats unless they are enabled, so the string "không có" ("none") gets into the
mailing system. The lesson: verify what you believe the schema is checking, with a bad sample.
8. Hands-on tutorial
8.1 Running the demo
cd academy-content/code-labs/l1-m05
python -m lab.demo l01
Output (copied from a real run, 2026-10-31):
valid ticket -> []
bad ticket ->
$: 'needs_human' is a required property
$: Additional properties are not allowed ('extra' was unexpected)
$.category: 'Refund' is not one of ['order_status', 'refund', 'damaged_item', 'account', 'other']
$.order_id: 'se1003' is not valid under any of the given schemas
$.priority: 9 is greater than the maximum of 5
$.summary: '' should be non-empty
priority 2.0 -> []
duplicate key parsed as -> {'category': 'refund', 'priority': 9}
Reading the output:
- The bad ticket has 6 errors, and all of them are reported at once, each with its path.
'Refund' is not one of [...]:enumis case-sensitive.order_idreports a generic error because it sits insideanyOf(§4.4).priority 2.0 -> []: valid according to the spec.- Duplicate names: Python keeps
"priority": 9, the last value.
8.2 Running the tests
python -m pytest tests/test_l01_schema.py -v
Expected result: every test passes. Read test_integer_edge_cases_follow_the_spec and
test_format_is_not_checked_unless_asked: these two tests record behaviour that is easy to misunderstand, so that
nobody "fixes" it by mistake.
8.3 Troubleshooting
| Symptom | Cause | Fix |
|---|---|---|
ModuleNotFoundError: jsonschema |
The requirements are not installed | python -m pip install -r requirements.txt |
SchemaError |
The schema itself is written wrongly | Read the message; it points at the wrong keyword |
| An invalid sample, yet the test still reports no error | The schema is too loose, or the keyword is format |
Check required and additionalProperties; enable check_formats=True |
9. Independent exercise
Problem: Write a schema for the return request that the application will receive from the model.
Requirements: complete exercises/test_l01_my_schema.py:
RETURN_REQUEST_SCHEMA:order_id(SE + 4 digits),items(an array of 1-5 elements, each element withskuand aquantityfrom 1 to 3),reason(enumdamaged,wrong_item,changed_mind),contact_email(format: email), no other field, every field required.- At least 3 valid samples, including one that sits exactly on the bounds.
- At least 5 invalid samples, each breaking exactly one rule, with the expected keyword in the error message.
Test data: make your own; emails use the domain example.com.
Deliverable: the completed test file.
Acceptance criteria: python -m pytest exercises/test_l01_my_schema.py passes; there is at least one sample for
an empty array and one sample for an extra field inside an element of items.
Hint: items has two meanings here: the name of your field, and the JSON Schema keyword items (the schema
for each element of an array). Each element is an object, so it also needs additionalProperties: false.
9.1 Extra exercise: samples wrong in exactly one place, in nested JSON (20-30 minutes)
Problem: ShopEasy's fictional delivery form has a nested object (address) and an array of objects
(parcels). To build a sample that is wrong in exactly one deep place without breaking the good
sample, you need a safe copy function.
Requirements:
- Run
python -m pytest exercises/test_l01_extra_one_change.pyonce, untouched:9 failed, 1 passed, and every failure starts withTODO. - Write
one_change(sample, path, value): it returns a new sample that differs fromsampleonly atpath(for example["parcels", 0, "weight_kg"]); avalueofDELETEremoves that key.samplemust not change. - In TODO 2, before running, write the exact line
validate()returns whenaddress.districtis deleted, then run to check it.
Acceptance criteria: 10 passed; each mutation in MUTATIONS gives exactly one error; GOOD is
intact after every test.
Hint: try {**sample} first to see test_original_is_untouched fail, then reread the example in
section 5.2. For TODO 2, ask: which keyword fails (required of which object), and where does the path
point once the key is gone?
9.2 Real-world scenario: reviewing the order schema of a food delivery app (fictional)
Context. The fictional app ComNhanh lets customers order food by chat message. The model extracts the message into JSON, then code creates the order and sends it to the restaurant. A developer hands you this schema to review:
{"type": "object",
"properties": {
"items": {"type": "array", "items": {"type": "object",
"properties": {"dish": {"type": "string"}, "qty": {"type": "integer", "minimun": 1}}}},
"phone": {"type": "string", "format": "phone"},
"address": {"type": "string"},
"note": {"type": "string", "maxLength": 200}},
"required": ["items", "phone"]}
With this schema, validate({"items": [{"dish": "phở", "qty": 0}], "phone": "abc"}, schema, check_formats=True) returns [].
Task: write (a) a list of the schema's problems, each with one line on the consequence for the customer or the restaurant; (b) at least 6 invalid samples, each breaking exactly one rule, with the expected result after the schema is fixed; (c) one question for the PO.
A good answer has:
- Spots the misspelled
"minimun": an unknown keyword is ignored, soqty: 0still passes (section 4.4) - Spots the missing
additionalProperties: falseon both the outer object and each item object - Spots that an empty order and an order without an address pass:
itemshas nominItems: 1,addressis not required,dishandqtyare not required - States that
formatis not checked by default, and"phone"is not a standard JSON Schema format, so apatternor a check in code is needed - Each invalid sample is wrong in one place only and has a concrete expected result (the path and the error's keyword)
- The question for the PO is checkable, for example the maximum quantity per dish or which phone formats are accepted
10. Knowledge check
0/20 done · Results are kept in this browser only.
P02 · True or false
P03 · Short answer
Why should each invalid sample break exactly one rule?
P04 · Short answer
What does Python parse the JSON {"priority": 1, "priority": 9} into? What does that mean for validation?
P05 · Short answer
(Scenario) The team's schema has no additionalProperties: false. Write a sample that shows the risk, and name the oracle you propose.
P06 · Match
P08 · Multiple choice
P09 · Spot the bug
The validate() function below was copied from lab/schemas.py but is missing one line. Find the bug.
def validate(instance, schema=TICKET_SCHEMA, check_formats=False):
validator = Draft202012Validator(schema, format_checker=FormatChecker() if check_formats else None)
errors = sorted(validator.iter_errors(instance), key=lambda e: (list(map(str, e.absolute_path)), e.message))
return [f"{e.json_path}: {e.message}" for e in errors]P10 · Recall
Lesson: L1-M04-L01P11 · True or false
P13 · Multiple choice
P14 · Fill in the blank
P15 · True or false
P16 · Match
P17 · Spot the bug
Here is a wrong solution to extra exercise §9.1. Find the defect.
def one_change(sample, path, value):
result = {**sample}
node = result
for key in path[:-1]:
node = node[key]
if value is DELETE:
del node[path[-1]]
else:
node[path[-1]] = value
return resultP18 · Select all that apply
P19 · Put in order
P20 · Apply now
In code-labs/l1-m05, run python -m pytest exercises/test_l01_extra_one_change.py once untouched, then do extra exercise §9.1 and run it again.
11. Summary
- Concepts: JSON; duplicate names in an object; JSON Schema 2020-12 and its main keywords; validating every error with its path; testing the schema itself.
- Skills: writing a schema; building samples that break exactly one rule; reading
jsonschemaerrors. - Pitfalls: believing that
formatis checked; forgettingadditionalProperties: false; thinking that2.0is not an integer; a misspelled keyword making the schema let everything through. - You can now: use JSON Schema as an oracle for the structured output of an LLM feature.
12. References
| ID | Title | Publisher | URL | Accessed | Relevance |
|---|---|---|---|---|---|
| R1 | LLM05:2025 Improper Output Handling | OWASP GenAI Security Project | https://genai.owasp.org/llmrisk/llm052025-improper-output-handling/ | 2026-10-31 | Zero trust towards model output |
| R2 | RFC 8259: The JavaScript Object Notation (JSON) Data Interchange Format | IETF | https://www.rfc-editor.org/rfc/rfc8259 | 2026-10-31 | Duplicate names in an object |
| R3 | JSON Schema Draft 2020-12 | json-schema.org | https://json-schema.org/draft/2020-12 | 2026-10-31 | The spec version used in this module |
| R4 | JSON Schema Validation (Draft 2020-12) | json-schema.org | https://json-schema.org/draft/2020-12/json-schema-validation | 2026-10-31 | type, enum, minimum, required |
| R5 | jsonschema documentation (4.26.0): Schema Validation; Handling Validation Errors | python-jsonschema | https://python-jsonschema.readthedocs.io/en/stable/validate/ and https://python-jsonschema.readthedocs.io/en/stable/errors/ | 2026-10-31 | iter_errors, formats not checked by default (validate page); json_path, message, validator (errors page) |
Key terms (English ↔ Vietnamese)
| English | Tiếng Việt |
|---|---|
| JSON Schema | Lược đồ mô tả JSON hợp lệ |
| Instance | Tài liệu JSON được kiểm tra |
| Keyword | Từ khóa của schema (type, required...) |
| Validation error | Lỗi kiểm tra hợp lệ |
| JSON path | Đường dẫn tới phần tử trong JSON ($.priority) |