Worked tutorial · about 35 minutes
Validate JSON outputs against an explicit contract
Inspect ten invented responses, separate parsing from field validation, and reproduce two acceptances and eight rejections with Python's standard library.
Original editorial exercise · fictional practice data · checked 25 October 2026
A response can look like JSON and still break the application that reads it. Your task is to write an acceptance contract, apply it to ten canned responses, and give a specific reason for each rejection. Everything here is invented practice data. You can finish offline with Python 3.10 or later; no model account or packages are required.
1. Save the input and commit to the contract
The outer file is valid JSON. Each raw field holds a separate response as text, preserving malformed syntax and repeated keys for inspection. The contract for each response is:
- Parse one complete JSON document. Reject repeated object keys and the nonstandard constants
NaN,Infinityand-Infinity. - Require a top-level object containing exactly
request_id,priority,labelsandneeds_review. request_idmust be a nonempty string, at most 24 characters, with no leading or trailing whitespace.prioritymust be an integer from 0 through 3. Boolean values are excluded.labelsmust be an array of at most three distinct strings drawn frombilling,schedulingandaccess. An empty array is valid.needs_reviewmust be a boolean.
Report the first failure in that order. These are exercise rules for an imaginary application; they are not a general JSON Schema implementation. A top-level array or an extra field can be valid JSON while failing this contract.
Inspect all ten raw responses
{
"dataset_note": "Canned fictional practice responses; not results of a model benchmark.",
"candidates": [
{
"id": "J01",
"raw": "{\"request_id\":\"case-01\",\"priority\":2,\"labels\":[\"billing\"],\"needs_review\":false}"
},
{
"id": "J02",
"raw": "{\"request_id\":\"case-02\",\"priority\":1,\"labels\":[],\"needs_review\":true,}"
},
{
"id": "J03",
"raw": "{\"request_id\":\"case-03\",\"priority\":1,\"needs_review\":true}"
},
{
"id": "J04",
"raw": "{\"request_id\":\"case-04\",\"priority\":1,\"labels\":[],\"needs_review\":true,\"comment\":\"check\"}"
},
{
"id": "J05",
"raw": "{\"request_id\":\"case-05\",\"priority\":true,\"labels\":[],\"needs_review\":true}"
},
{
"id": "J06",
"raw": "{\"request_id\":\"case-06\",\"priority\":1,\"labels\":[\"billing\",\"billing\"],\"needs_review\":true}"
},
{
"id": "J07",
"raw": "{\"request_id\":\"case-07\",\"priority\":1,\"labels\":[\"urgent\"],\"needs_review\":true}"
},
{
"id": "J08",
"raw": "{\"request_id\":\"case-08\",\"priority\":1,\"priority\":2,\"labels\":[],\"needs_review\":true}"
},
{
"id": "J09",
"raw": "{\"request_id\":\"case-09\",\"priority\":NaN,\"labels\":[],\"needs_review\":true}"
},
{
"id": "J10",
"raw": "{\"request_id\":\"case-10\",\"priority\":0,\"labels\":[],\"needs_review\":true}"
}
]
}2. Predict failures before running code
- Mark each response accepted or rejected. For a rejection, identify the exact syntax or field rule that fails.
- Explain why a missing
labelsfield differs from a valid empty array. Decide what to do with J08's two priority values before allowing a parser to choose one. - Count accepted responses, then change only J05's priority from
trueto1in a copy. Predict the new count.
Python's default decoder keeps the last value when object keys repeat, and accepts nonfinite constants. The supplied validator uses object_pairs_hook and parse_constant to reject them. Its priority check uses type(value) is int because bool is an integer subtype in Python. See the official JSON decoder documentation and Python's boolean type reference.
3. Run the validator and compare the answer
Place all downloads in the same folder and run:
python validate_outputs.py candidates.json
python validate_outputs.py candidates.json --check answer_key.json The script reads files and prints JSON. The second command exits with status 0 for an exact match and status 1 for a mismatch. It does not repair or overwrite the input.
Show the worked answer
J01 and J10 pass: 2 accepted, 8 rejected. Zero priority and an empty labels array are allowed. Changing only J05's priority to 1 produces 3 accepted responses.
| Response | Reason | Correction to discuss |
|---|---|---|
| J02 | Trailing comma: invalid JSON | Remove the comma after the final value. |
| J03 | Missing labels key | Supply a labels array after checking the intended value. |
| J04 | Unexpected comment key | Align the producer with the agreed keys. |
| J05 | Boolean priority | Supply an integer, rather than silently coercing true to 1. |
| J06 | Repeated label | Supply distinct labels. |
| J07 | Label outside the allowed set | Review the intended label; urgent is not accepted here. |
| J08 | Repeated priority key | Resolve the conflict with the producer. |
| J09 | Nonfinite constant NaN | Supply a permitted integer after reviewing the missing value. |
Show the complete standard-library solution
"""Offline contract validator for invented responses. Python 3.10+, stdlib only."""
import argparse
import json
from pathlib import Path
KEYS = {"request_id", "priority", "labels", "needs_review"}
LABELS = {"billing", "scheduling", "access"}
class ContractError(ValueError):
pass
def unique_object(pairs):
result = {}
for key, value in pairs:
if key in result:
raise ContractError("duplicate_key")
result[key] = value
return result
def reject_constant(value):
raise ContractError("nonfinite_number")
def first_error(raw):
try:
obj = json.loads(raw, object_pairs_hook=unique_object,
parse_constant=reject_constant)
except json.JSONDecodeError:
return "invalid_json"
except ContractError as exc:
return str(exc)
if type(obj) is not dict:
return "top_level_object"
if set(obj) != KEYS:
return "keys_mismatch"
name = obj["request_id"]
if type(name) is not str or not 1 <= len(name) <= 24 or name.strip() != name:
return "request_id_format"
priority = obj["priority"]
# bool subclasses int: isinstance(True, int) would incorrectly accept it.
if type(priority) is not int or not 0 <= priority <= 3:
return "priority_type_or_range"
labels = obj["labels"]
if type(labels) is not list or len(labels) > 3:
return "labels_shape"
if any(type(label) is not str or label not in LABELS for label in labels):
return "labels_value"
if len(set(labels)) != len(labels):
return "labels_duplicates"
if type(obj["needs_review"]) is not bool:
return "needs_review_type"
return "ok"
def evaluate(data):
results = []
for case in data["candidates"]:
reason = first_error(case["raw"])
results.append({"id": case["id"], "accepted": reason == "ok", "reason": reason})
accepted = sum(row["accepted"] for row in results)
return {"total": len(results), "accepted": accepted,
"rejected": len(results) - accepted, "results": results}
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("input", type=Path)
parser.add_argument("--check", type=Path, help="Compare with an answer JSON file")
args = parser.parse_args()
result = evaluate(json.loads(args.input.read_text(encoding="utf-8")))
print(json.dumps(result, indent=2, allow_nan=False))
if args.check and result != json.loads(args.check.read_text(encoding="utf-8")):
parser.exit(1, "Answer mismatch: compare the printed fields with your answer.\n")
if __name__ == "__main__":
main()
4. Explain what passing establishes
A passing response satisfies this small structural contract. It does not establish that the priority or labels are correct for a real request; the file contains no source request to check. A useful handoff separates “accepted by the contract” from “verified against evidence.” Do not silently fix a rejected response and record it as an original success.
As a boundary check, try priority 3, priority 4, priority 1.0, and needs_review: "true" in separate copies. The expected decisions are pass, reject, reject, reject when the other fields remain valid. The validator deliberately distinguishes JSON integer syntax from a decimal number.
To practice evidence rather than structure, continue to the retrieved-answer audit. For an independent calculation exercise, try the fictional token budget.
Sources and scope
The contract, responses and answer key are original editorial practice material. The linked Python documentation supports the decoder and type behavior; it does not certify these application rules. Sources checked 25 October 2026.