A structured routing decision.
Parse JSON, validate a small schema, and keep invalid model output away from downstream actions.
Why this workflow exists.
A support router may need one category that software can consume. If generated prose is passed directly into an action, unusual wording can cause silent mistakes. A constrained object is easier to validate. This recipe shows the three checks in order: parse text, check fields, and accept only known values.
The result is a routing proposal, not an automated transfer of a real ticket. That separation leaves room for task evaluation and human oversight when the cost of a wrong route is high.
Code context. Python 3 standard library only; all input strings are included in the script.
The whole example.
import json
ALLOWED = {"billing", "access", "other"}
def parse_route(raw):
try:
value = json.loads(raw)
except json.JSONDecodeError:
return {"status": "invalid_json"}
if not isinstance(value, dict) or set(value) != {"category", "reason"}:
return {"status": "invalid_schema"}
if value["category"] not in ALLOWED:
return {"status": "invalid_category"}
if not isinstance(value["reason"], str) or not value["reason"].strip():
return {"status": "invalid_reason"}
return {"status": "candidate", "route": value}
samples = [
'{"category":"access","reason":"The user cannot sign in."}',
'{"category":"refund","reason":"Mentions a refund."}',
'not json',
]
for sample in samples:
print(parse_route(sample))What each stage does.
json.loads turns a JSON string into a Python value. It can raise a parsing error, which becomes invalid_json. A valid JSON list still fails because the contract requires a dictionary with exactly two fields. The allowed set then checks category, and the final check requires a nonempty reason.
The first sample becomes a candidate. The second fails because refund is not an allowed category, even though the JSON is valid. The third fails at parsing. Named statuses make it clear which layer failed and support useful monitoring.
What the output means.
The script prints one candidate and two distinct failures. A production application could route failures to human review and count which validation rule fails most often.
Where the example stops.
The validator cannot tell whether access is the correct category for the first message. That requires labelled cases or a reviewer. A valid object must still pass permission and business rules before any real ticket is changed.