Validate the JSON a model returns
Asking a model for JSON does not guarantee it arrives well formed: fields go missing or numbers come back as text. Check it before you use it.
Write validate(obj, schema) for schemas shaped like { type: 'object', required: [...], properties: { key: { type: 'string' | 'number' | 'boolean' } } }. Return an array of errors, empty when everything is valid:
'expected object'(and nothing else) whenobjis not an object:null, an array or a primitive.'missing: key'for every key inrequiredthat is absent.'key: expected type'for every present property with the wrong type.
You already have SCHEMA and MODEL_REPLY, a real reply with confidence as text.
Challenges 0/5
- A valid object returns []
- Reports missing required fields
- Reports wrong types
- Rejects null, arrays and strings
- Collects several errors and allows absent optionals
function validate(obj, schema) {
const errors = [];
// 1. not an object -> ['expected object']
// 2. required keys -> 'missing: key'
// 3. typeof each present property -> 'key: expected type'
return errors;
}
console.log(validate(MODEL_REPLY, SCHEMA));Tab indents, Ctrl+Z undoes. To leave the editor with the keyboard: Esc, then Tab.
Why this matters
A model that returns well-formed JSON can still return the wrong JSON: a field is missing, the total arrives as text, the priority is none of the three allowed. If that object goes straight into your database or another tool, the error surfaces far from its origin and is hard to find. Validating at the boundary, with a message that says which field fails, is also what lets you hand the error back to the model and ask it to correct itself. How much it helps to enforce the schema from the server is measured in Ollama structured output with a JSON schema.
Go deeper: the JSON Schema reference →
This in production, with your data? Let's talk for 15 minutes →