Extract Fields With a JSON Schema and Validate Them
Define a schema for a fictional repair request, check the response locally and keep format validation separate from factual review.
Difficulty Intermediate
Prerequisites
Use Python 3 in an isolated virtual environment with jsonschema installed. Work with a text editor and a local or hosted assistant. No GPU is needed for validation.
Define the extraction contract
Save this example as schema.json. Both properties are required. An unknown identifier must be represented as null.
{
"type": "object",
"properties": {
"ticket_id": {"type": ["string", "null"], "pattern": "^LAB-[0-9]+$"},
"category": {"enum": ["display", "audio", "other"]}
},
"required": ["ticket_id", "category"],
"additionalProperties": false
}
Give the assistant the schema and this synthetic source: “Ticket LAB-42. The speakers are silent.” Ask for a JSON object with no code fences. Save the exact response as result.json. If your assistant offers native schema-constrained output, verify that it supports every keyword used.
Validate before importing
python -c 'import json; from jsonschema import Draft202012Validator; s=json.load(open("schema.json")); Draft202012Validator.check_schema(s); Draft202012Validator(s).validate(json.load(open("result.json"))); print("Accepted by schema")'
Manually check that the identifier and category match the source. A well-formed object with LAB-99 can satisfy the schema and still be wrong. Keep the import in preview mode until this evidence check is complete.
Troubleshooting and practice
A JSON parse error may come from code fences or a trailing comma. Reject the response or retry with the first error as feedback. Add a property called notes and verify that validation fails. Then remove the identifier from the source and expect a null value without dropping the key. This example uses small trusted files. Limit input size and reject duplicate keys when accepting untrusted data in an application.