Skip to content

Getting Structured Output From LLMs

How to get JSON and other machine-readable output reliably from a language model, and how to validate it.

Editorial team 2 min read

When a program will use a model's answer, free-form prose isn't good enough. You need predictable, structured output.

Describe the Exact Shape

Show the structure you want, with field names, types and rules:

Extract these fields from the invoice. Reply with JSON only:
{"supplier": string, "invoice_date": "YYYY-MM-DD", "total": number, "currency": string}
Use null for anything not in the invoice.

Use the API's Structured-Output Features

Most major model APIs offer ways to enforce structure: JSON modes, structured outputs that follow a JSON schema, or tool (function) calling, where the model fills in arguments for a function you define. These are more reliable than instructions alone.

Always Validate

Treat model output like any untrusted input:

  • parse it and catch errors;
  • validate against a schema (for example with Pydantic or JSON Schema);
  • check business rules — dates in range, totals that add up;
  • retry with the validation error included, or send to a person, when it fails.

Design Tips

  • Keep schemas as simple as the task allows.
  • Use enums for fixed choices.
  • Ask for null rather than guesses when information is missing.
  • For long documents, extract section by section.

Reasoning Before Answering

If a task needs reasoning, let the model think in a separate field or step before producing the final structured answer, rather than squeezing reasoning into the JSON values.

More in Generative AI

All Generative AI guides →
Generative AI Guide · 2 min

Prompt Engineering Fundamentals

The building blocks of a good prompt — context, task, constraints and format — with before-and-after examples.

Generative AI 2 min read 24 Jul 2026

Generative AI Guide · 2 min

Few-Shot Prompting With Examples

Showing a model a few examples of the input and output you want is often clearer than describing it. How to choose good examples.

Generative AI 2 min read 23 Jul 2026

Generative AI Guide · 2 min

Why Language Models Hallucinate

What hallucination is, why it happens, and practical ways to reduce and catch it.

Generative AI 2 min read 21 Jul 2026

Generative AI Guide · 2 min

Retrieval-Augmented Generation (RAG) Explained

How RAG grounds a language model's answers in your own documents, the components involved, and where it goes wrong.

Generative AI 2 min read 20 Jul 2026