What Is Structured Output? Getting Reliable JSON from LLMs

Ask a language model for a list of products and you get a friendly paragraph. Ask your code to read that paragraph and it breaks. Structured output from LLMs fixes that gap: instead of free-form text, the model returns data in a shape your application can parse, validate, and store, usually JSON that matches a schema you define.

It matters any time model output feeds another system: a chatbot that needs to call a function, a pipeline that extracts fields from documents, or a classifier that must return exactly one label. If the output has to be machine-readable, asking nicely in the prompt is not enough. You need the model to commit to a structure, and you need to check its work.

What Structured Output from LLMs Actually Means

Structured output is model output that follows a format you set in advance. You describe the shape, the field names, the types, and which fields are required, and the model fills in the values. The result is data you can feed straight into code: no regular expressions, no string splitting, no hoping the model remembered to use quotes.

There is a real difference between asking for JSON and getting structured output. “Reply in JSON” is a request the model can ignore or half-follow. Structured output is a constraint: the provider’s API enforces the format while the model generates, so the response comes back as valid JSON that matches your schema. The distinction matters most in production, where one malformed response can break a whole pipeline.

Why Plain Text Breaks Your Code

Unstructured model text fails in predictable ways. The model wraps JSON in markdown fences, adds a sentence of commentary after the closing brace, drops a required field, or returns a number as a string. Any one of these is a small slip for a human reader and a hard error for a JSON parser.

The cost shows up at the worst time: in production, on real user input, when a missing field turns into a 500 error or a silent wrong value in your database. That is why teams that ship AI features test an AI feature before shipping it to users, with real inputs and assertions on the output shape, not just a glance at a few good replies.

Three Ways to Get Structured Output

Most providers now offer at least one of these. They differ in how strongly the format is enforced and how much work they ask of you.

1. JSON mode

JSON mode tells the model to reply with JSON and nothing else. It is the simplest option and it works well for quick prototypes, but it guarantees nothing about the shape: keys, types, and required fields are still up to the model. Treat JSON mode as a nudge, not a contract.

2. Function calling

With function calling, you describe a function and its parameters, and the model returns the arguments as a JSON object. The structure comes from the function definition, so the model fills in a form instead of writing prose. This is the natural fit when the model needs to trigger an action, look something up, or hand data to another system, and it is the pattern behind most chatbots that answer from your own documents.

3. JSON Schema and constrained decoding

The strongest option is to pass a full JSON Schema with your request. The provider then constrains the model’s output token by token so the result cannot violate the schema. Fields, types, enums, and required keys are enforced during generation, not checked afterwards. If your provider supports it, a json schema for llms is the default to reach for in production.

How to Write a Schema LLMs Can Follow

A schema is a contract, and like any contract it should be short and explicit. Keep it small: a handful of fields beats a 40-field object the model has to hold in mind. Prefer flat objects over deep nesting, use enums for anything with a fixed set of values, and write a one-line description for every field, because the model reads those descriptions as instructions.

Mark only the fields you truly need as required. Everything else should be optional, or the model will invent values to fill gaps it has no data for. A schema for extracting a product might look like this:

{
  "type": "object",
  "properties": {
    "name": {"type": "string"},
    "price": {"type": "number"},
    "in_stock": {"type": "boolean"},
    "category": {"type": "string", "enum": ["books", "electronics", "clothing"]}
  },
  "required": ["name", "price"]
}

Notice what the schema does not ask for: no free-text summary, no nested variants, no field the model would have to guess. If a value is uncertain, leave it out of the schema and let your code handle the gap.

Validating LLM JSON Before You Trust It

Even with schema enforcement, validate every response on your side before it touches your database. LLM json validation is a two-step job: parse the JSON, then check it against the same schema with a validator such as Zod, Pydantic, or Ajv, and reject anything that fails. A rejected response is not a failure: it is a signal to retry, ideally by sending the validation error back to the model so it can fix its own mistake.

That retry loop is the single most effective reliability trick in this whole article. One retry with a concrete error message (“field ‘price’ must be a number, got a string”) fixes most malformed outputs, and it costs a fraction of a second. Validation plus retry is also a form of guardrail: it catches wrong shapes before they become wrong data, which matters when the output feeds billing, search, or user-facing pages. If you want the wider picture, read our guide on how to stop AI hallucinations in your app with grounding, citations, and guardrails.

Common Failures and How to Fix Them

Failure What you see Fix
Markdown fences Triple backticks around the output Strip fences in code, or switch to schema mode
Missing field Required key absent Mark it required, describe it, retry with the error
Wrong type “42” instead of 42 Strict types in the schema; coerce only at the boundary
Extra keys Fields you never asked for Allow and ignore them, or strip them before storage
Truncated output JSON cuts off mid-object Raise the token limit and shrink the schema

When Structured Output Isn’t the Right Tool

Structure is a trade-off. It adds latency, costs tokens, and forces the model into a narrow shape. For creative writing, open-ended chat, or a summary a human will read, plain text is the better choice. The same goes for exploratory work where you do not yet know what fields matter: forcing a schema too early hides information instead of organizing it.

A good rule: use structured output when another system consumes the result, and plain text when a person does. The prompt patterns that work for one do not always transfer to the other, so keep your prompts for structured calls short and specific. Our collection of prompt engineering patterns for developers is a useful starting point for both cases.

Frequently Asked Questions

Is structured output the same as function calling? Not quite. Function calling is one way to get structured output: the model fills in a function’s arguments. Schema mode is the other main route, and it works without any function definition.

Can structured output stop hallucinations? No. It controls the shape of the answer, not whether the facts inside it are true. A model can return perfectly valid JSON with a made-up price. Grounding and retrieval are what fix facts; structure only fixes format.

Does JSON mode guarantee valid JSON? With schema enforcement, effectively yes for the shape you defined. With plain JSON mode, usually but not always, so validate every response anyway.

Start with schema mode where your provider supports it, keep schemas small and explicit, and validate every response with a retry loop. That combination turns LLM output from text you hope to parse into structured llm responses you can build on.

Ditulis oleh

Firdaus Safari Putra

Founder, PT FirKaizen Digital Solutions

Firdaus Safari Putra adalah founder PT FirKaizen Digital Solutions. Ia membangun dan mengoperasikan infrastruktur server di balik panduan ini, dan menulis berdasarkan apa yang benar-benar ia jalankan, uji, dan ukur — bukan teori.