Getting reliable, schema-valid JSON from an LLM is one of the most common production requirements. The naive approach — asking the model to 'respond in JSON' — works ~90% of the time but fails just often enough to break your pipeline. Here's how to get to 99.9%+ reliability.
1. Use strict JSON schema mode (OpenAI / Gemini)
OpenAI's strict schema mode and Gemini's responseSchema parameter constrain the model at the token level — invalid tokens are masked before they can be generated. This gives near-zero malformed JSON rate. The trade-off: your schema must be valid JSON Schema (no default values, no $ref, all required fields must be listed). But for production systems, this is the right choice.
- OpenAI: `response_format: { type: "json_schema", json_schema: { strict: true, schema: {...} } }`
- Gemini: `generationConfig: { responseMimeType: "application/json", responseSchema: {...} }`
- All fields in the schema must appear in the output — use `{ type: ["string", "null"] }` for optional fields
- Strict mode may refuse schemas that use $ref, definitions, or some complex combinators
2. Use Pydantic / Zod for automatic schema generation
Defining JSON schemas by hand is error-prone. Use Pydantic (Python) or Zod (TypeScript) to define your data model in code, and let the library generate the JSON schema automatically. OpenAI's `.parse()` method handles the full round-trip: takes a Pydantic/Zod class, converts to schema, sends to API, parses response back into typed object. This is the best developer experience available.
Tip
Pydantic v2 with OpenAI Python SDK: `from openai import OpenAI; client.beta.chat.completions.parse(model=..., messages=..., response_format=MyPydanticModel)`. The result is a fully typed Python object, not raw JSON.
3. Claude: use tool use, not JSON prompting
Claude does not have a native JSON mode. The recommended pattern is to define a tool whose parameters match your desired schema, then ask Claude to call it. Claude's tool use is very reliable — it rarely produces invalid parameter values. This works with any schema that can be expressed as JSON Schema, and handles optional fields well via `anyOf: [type, {type: 'null'}]`.
4. JSON mode (without strict schema)
JSON mode guarantees valid JSON syntax but lets the model choose the structure. Use it when you want JSON output but can accept variable schemas — for example, when extracting key-value pairs from documents where you don't know the keys in advance. Set `response_format: { type: 'json_object' }` on OpenAI; Claude doesn't have this but you can instruction-prompt it reliably for simple cases.
5. Constrained decoding for self-hosted models
If you're running your own inference (vLLM, Ollama, Transformers), you can enforce schemas at the token level using grammar-based decoding. Libraries like Outlines and LM Format Enforcer mask invalid tokens during sampling, giving 100% schema compliance regardless of model capability. This is the only way to guarantee valid output from smaller open-source models like Llama 3.1 8B.
6. Schema design tips
Schema design affects output quality. Narrow schemas (few fields, simple types) produce better results than complex ones. Use enum arrays to constrain categorical fields — `{ type: 'string', enum: ['positive', 'negative', 'neutral'] }` outperforms free-text sentiment fields. Add descriptions to your schema properties; models use them to fill values correctly.
- Keep schemas as flat as possible — nested objects reduce accuracy
- Use enums for any field with a fixed value set
- Add `description` to schema properties — the model uses them
- Avoid arrays of objects at depth > 2 — accuracy drops significantly
- Test with edge-case inputs that might confuse the model
7. Validation and fallback strategy
Even with strict schema mode, validate the output before using it — schema compliance doesn't mean semantic correctness. Use Pydantic validators or manual checks for business-logic constraints. For non-strict flows, wrap your JSON parse in a try-catch and retry with the parse error as feedback: 'Your previous response was invalid JSON: {error}. Try again.' One retry resolves >95% of failures.
Tip
Log all schema validation failures with the prompt and raw model output. Patterns in failures will reveal schema design issues or model limitations you can address.
