How to Get Reliable JSON From LLMs: Schemas, Validation, Retries
Getting valid JSON from an LLM takes more than asking nicely. Use schemas, structured output modes, validation and retries, and avoid the usual failure modes.
Structured output
Structured output prompting is how you get a model to answer in a fixed, machine-readable shape, usually JSON that matches a schema. The reliable approach combines a clear schema, an example, the provider’s structured-output or JSON mode when available, and validation in your code with a retry when parsing fails.
Your app parses the model’s JSON, but sometimes the reply starts with “Sure! Here is the JSON:”. What is the most robust fix?
Your app parses the model’s JSON, but sometimes the reply starts with “Sure! Here is the JSON:”. What is the most robust fix?
B. Use the API’s structured-output / JSON mode with a schema and validate the result Native structured-output modes constrain the reply to valid JSON, and schema validation catches the rest. String hacks break as soon as the wording changes.
Give a schema and an example, use the provider’s structured-output or JSON mode if it has one, and validate the reply in code. On failure, retry with the validation error included.
Tell it explicitly, for example “use null when the document does not say”. Otherwise models tend to fill gaps with plausible guesses.
Getting valid JSON from an LLM takes more than asking nicely. Use schemas, structured output modes, validation and retries, and avoid the usual failure modes.
How LLM tool calling works, how to write tool descriptions models use correctly, how agent loops run and stop, and the failures to plan for in agents.
Zero-shot prompts give only instructions; few-shot prompts add examples. Learn when examples improve output, and when they cause copying, bias and drift.
Short quizzes on real prompting decisions, with an explanation for every answer. Free to start on iPhone and Android.