← Lesson
JSON Schema for Tools
Joeven
Run
Reset
Python loads on first run
SCHEMA = { "name": "refund", "required": ["invoice_id", "amount_cents"], "properties": { "invoice_id": {"type": "string"}, "amount_cents": {"type": "integer", "minimum": 1, "maximum": 1000000}, "reason": {"type": "string", "enum": ["duplicate", "outage", "courtesy"]}, }, } def type_ok(val, spec): t = spec.get("type") if t == "string": return isinstance(val, str) if t == "integer": return isinstance(val, int) and not isinstance(val, bool) return True def validate(args, schema): errors = [] props = schema["properties"] for key in schema["required"]: if key not in args: errors.append("missing " + key) for key, val in args.items(): if key not in props: errors.append("unknown field " + key) continue spec = props[key] if not type_ok(val, spec): errors.append(key + " bad type") if "enum" in spec and val not in spec["enum"]: errors.append(key + " not in enum") if "minimum" in spec and isinstance(val, int) and val < spec["minimum"]: errors.append(key + " below minimum") if "maximum" in spec and isinstance(val, int) and val > spec["maximum"]: errors.append(key + " above maximum") return errors samples = [ {"invoice_id": "INV-17", "amount_cents": 4000, "reason": "duplicate"}, {"invoice_id": "INV-17", "amount_cents": 4000, "reason": "because I said so"}, {"amount_cents": 1}, {"invoice_id": "INV-17", "amount_cents": -5}, ] for s in samples: errs = validate(s, SCHEMA) print(s, "->", errs or "ok")
Run to execute this in your browser. Nothing is sent to a server.