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) when obj is not an object: null, an array or a primitive.
- 'missing: key' for every key in required that 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));Go deeper: the JSON Schema reference →
This in production, with your data? Let's talk for 15 minutes →