What is it?
JSON validation means verifying that a document is syntactically valid JSON and that it matches the shape your program expects. Syntax alone is not enough: {"ok": true} parses but may be useless if you needed an id string.
Why it matters
AI systems emit and consume JSON constantly — API bodies, tool arguments, structured output. Unvalidated data causes security bugs (SQL/command injection via arguments) and confusing model failures. Validation belongs at trust boundaries.
How to do it
- Parse with the language's JSON library; on failure, return 400.
- Confirm the root type (object vs array).
- Check required fields exist.
- Check types (string/number/boolean/array/object) and ranges (min/max, enum).
- Optionally enforce a JSON Schema with a validator library.
- Strip unknown fields if your policy is deny-by-default.
- Only then pass data to databases, shells or model prompts.
For TypeScript clients, combine types with runtime checks (TypeScript Types for an API Client). For Python pipelines, validate after json.load (JSON and CSV Handling for AI Work in Python).
Example
function assertChatBody(data) {
if (!data || typeof data !== "object") throw new Error("body must be object");
if (typeof data.message !== "string" || !data.message.trim()) {
throw new Error("message required string");
}
if (data.temperature !== undefined) {
if (typeof data.temperature !== "number" || data.temperature < 0 || data.temperature > 2) {
throw new Error("temperature out of range");
}
}
return { message: data.message.trim(), temperature: data.temperature };
}
Schema-based validators scale better once many endpoints share definitions.
When to use it
Validate every external JSON input: browser requests, model tool arguments, webhook bodies, files uploaded as .json. Skip only for throwaway local experiments.
Practical notes
Schema strategies: start with hand-written asserts for two or three fields; graduate to JSON Schema when multiple services share contracts. Version your schemas ('chat.request.v1') so old clients fail clearly. Validate again after the model returns structured output — models can omit required keys or invent enums. For tool arguments, validation failures should return a readable tool error so the model can retry, not a stack trace. Property tests can generate random invalid payloads to ensure your API stays fail-closed. Do not rely on a browser JSON formatter alone; server-side validation is mandatory even if a client tool helped you inspect a payload while debugging.
Common mistakes
- Using
JSON.parseand assuming the shape is right. - Validating only in the UI and not on the server.
- Allowing huge payloads without size limits.
- Trusting model-produced JSON without a schema (models can omit fields).