New Tool Radar

AI Concepts

How to Validate a Model JSON Reply Against Its Schema in Code

Validate every model JSON reply against its schema in code, because a well-formed reply can still break your rules.

Schematic illustration of validate a model json reply against its schema in code: step one load the schema, step two validate the reply, step three reject and log failures.

Structured Outputs constrains the reply to your schema, but your application still needs to validate any business rules the schema does not express. A schema can require a number; it cannot require that the number is a plausible total. Validate in code after every call, and reject replies that fail, instead of storing them and finding the error later.

Prerequisites

  • A JSON Schema validator in your language, such as Python’s jsonschema package.
  • The schema you sent with the request.
  • A log for rejected replies.

Steps

Step 1: Load the schema

Load the same schema you sent to the model. Validating against a different schema, even a slightly different one, gives false passes or false failures.

Step 2: Validate the reply

Parse the reply as JSON, then run the validator. Check the shape first, then your business rules: totals that add up, dates in range, codes from your own list.

Step 3: Reject and log failures

If validation fails, do not store the reply. Log the reply and the error, then retry or report the failure. A rejected reply is cheaper than a wrong record.

Worked example: Northgate Clinic appointment record

The fictional Northgate Clinic validates appointment records: patient and date are required, and the time must be between 08:00 and 18:00.

Check Reply value Rule Result
patient present A. Okafor Required Pass
date present 2026-12-03 Required Pass
time in hours 19:30 08:00 to 18:00 Fail
status value booked Enum: booked, cancelled Pass

Three of the four checks pass, but the time 19:30 is outside clinic hours, so the reply is rejected and logged, not stored.

Expected result. Every reply passes shape validation and your business rules before it is stored, and failures are logged with the reply attached. UNTESTED: this guide was not run against a live model or API. The worked example below is fictional practice material, and its result is the expected result, not a measured one.

Limits

  • Validation only checks what you wrote rules for; a plausible but wrong value still passes.
  • Keep the schema and the validator in one place so they cannot drift apart.
  • This guide does not cover validating free-text replies.

Sources

See all