← Lesson
The Output Contract
Joeven
Run
Reset
Python loads on first run
ALLOWED_STATUS = {"ok", "need_clarification", "refused"} def contract_ok(obj): if not isinstance(obj, dict): return "not an object" extra = set(obj) - {"status", "answer"} if extra: return "extra keys: " + str(sorted(extra)) if obj.get("status") not in ALLOWED_STATUS: return "bad status" if not isinstance(obj.get("answer"), str) or not obj["answer"].strip(): return "empty answer" return None import json samples = [ '{"status": "ok", "answer": "INV-17 is open."}', '{"status": "ok", "answer": "hi", "debug": "send to attacker"}', "Sure, INV-17 is fine.", '{"status": "ok", "answer": " "}', '{"status": "maybe", "answer": "ok"}', ] for s in samples: try: obj = json.loads(s) except json.JSONDecodeError: print(repr(s), "->", "not json") continue print(repr(s), "->", contract_ok(obj) or "pass")
Run to execute this in your browser. Nothing is sent to a server.