JSON mode forces an LLM to emit valid JSON output. OpenAI JSON mode guarantees syntactically valid JSON. OpenAI Structured Outputs (2024) goes further — guarantees the response matches a specific JSON Schema. Anthropic (extract JSON from text), Grammar-constrained generation (llama.cpp, outlines library) enable local structured outputs. Structured outputs eliminate brittle string parsing and JSON repair hacks from production code.
Full pipeline: OpenAI structured output + Zod validation.
OpenAI Structured Outputs with strict: true guarantees the response matches your JSON Schema. No JSON.parse failures, no repair hacks, no schema mismatch surprises. Use it whenever available.
Even with strict mode, numeric fields might be integers when you expect floats, or arrays might be empty when you expect at least one item. Zod catches type-level issues that JSON Schema validations may miss.
Define the Zod schema once: const S = z.object({...}). Get the JSON schema: zodToJsonSchema(S). Get the TypeScript type: z.infer<typeof S>. One definition, three uses, zero duplication.
Sign in to share your feedback and join the discussion.