AI ENGINEERING · PROMPTING AND STRUCTURED OUTPUT · PROMPTING · 9 OF 35

Structured Output: Getting Reliable JSON From an LLM

How to get output your code can trust: asking for JSON versus JSON mode versus schema-enforced output, how constrained decoding masks invalid tokens, a worked invoice schema and extraction, enums and nullable required fields, small flat schemas, validating values and retrying with errors, forcing a tool call, and streaming partial JSON.

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17
  18. 18
  19. 19
  20. 20
  21. 21
  22. 22
  23. 23
  24. 24
  25. 25
  26. 26
  27. 27
  28. 28
  29. 29
  30. 30
  31. 31
  32. 32
  33. 33
  34. 34
  35. 35
1 / 17

Press play to hear the narration, or step through at your own pace.

Key takeaways

  • Enforce the schema
  • enums and nulls
  • small and flat
  • validate the values
  • retry with errors
  • act on final JSON

Notes

Why structure

Picture an accounts payable feature. Invoices arrive as PDFs, and your app must save the vendor, dates, line items and total into a database. A person is happy with: the total is about two hundred and fifty dollars, due next month. Your code is not. It needs a number, a currency code and a date in a fixed format. And if the model opens with, sure, here is the JSON, your parser throws an error before it reads a single field.

For people vs for code
a person is fine with:
  "The total is about 250
   dollars, due next month"

code needs:
  {"total": 247.80,
   "currency": "USD",
   "due_date": "2026-12-15"}

one stray word breaks the parser

The idea

There are three levels of control. Level one, ask in the prompt: reply only with JSON shaped like this example. It usually works, but nothing guarantees it. Level two, JSON mode: the reply always parses as JSON, but may not have your fields. Level three, schema enforced output: you pass a JSON Schema, and the reply is guaranteed to match it. Most providers offer this, often called structured outputs or strict mode. Use it whenever you can.

Three levels of control
  • 1 ask in the prompt "reply only with JSON like…" usually works, no guarantee
  • 2 JSON mode always parses, any shape
  • 3 schema-enforced output always matches your schema (constrained decoding)
  • use level 3 when it is offered

Just asking

Here is how prompt only JSON breaks. A friendly sentence before the object. Markdown code fences around it. A number written as a string with the currency glued on. Due date renamed to payment due. Or the reply simply stops halfway because it hit the output token limit. Each one is rare on a single call. But at a million calls a day, a failure rate of one in a thousand is a thousand broken records, every day.

How prompt-only JSON breaks
Sure! Here is the JSON:
```json
{"vendor": "Acme Ltd",
 "total": "247.80 USD",
 "payment_due": ...

• preamble and code fences
• a number written as a string
• a key renamed or missing
• cut off at the max token limit

Constrained decoding

How can a provider guarantee the shape? Constrained decoding. The schema is compiled into a grammar, a small state machine that knows which characters may come next. At each step the model scores every possible next token as usual. Then the decoder sets every token that would break the grammar to zero and renormalises the rest. Here currency must be U S D, E U R or I N R. Dollar is blocked, so U S rises from fifty to about seventy one percent.

Masking the next token
written so far:  {"currency": "
schema: enum USD, EUR, INR

token     prob    allowed?
"US"      0.50    yes
"EUR"     0.20    yes
"Dollar"  0.25    no → 0
"\n"      0.05    no → 0

renormalise the allowed ones:
  US 0.50/0.70 ≈ 0.71, EUR ≈ 0.29

An invoice schema

Here is a schema for the invoice. An object with a vendor string, a date string, a currency that must be one of three codes, and an array of line items, each with a description, a quantity and a unit price. Then tax and total as numbers. Every field is required, and additional properties false stops the model inventing extra keys. Add a short description to each field, like: the issue date, as year, month, day. Descriptions guide the model exactly like a prompt.

Invoice schema (trimmed)
{"type": "object",
 "properties": {
  "vendor":   {"type": "string"},
  "date":     {"type": "string"},
  "currency": {"enum": ["USD","EUR","INR"]},
  "items":    {"type": "array", "items":
     {desc, qty, unit_price}},
  "tax":      {"type": "number"},
  "total":    {"type": "number"}},
 "required": [every field],
 "additionalProperties": false}

A worked extraction

Run it on a real invoice. Acme Limited, invoice four five seven, third of November twenty twenty six. Two cable kits at forty five dollars, one router at a hundred and twenty. Tax at eighteen percent is thirty seven eighty, total two hundred and forty seven eighty. The model returns exactly the schema: the vendor, the date as year month day, currency U S D, two line items with real numbers, then tax and total. No preamble, no fences, nothing to clean.

In and out
in: "Acme Ltd   Inv 0457   3 Nov 2026
  2 x Cable kit   @ 45.00
  1 x Router      @ 120.00
  Tax 18% 37.80   Total USD 247.80"

out: {"vendor": "Acme Ltd",
 "date": "2026-11-03",
 "currency": "USD", "items": [
  {"desc": "Cable kit", "qty": 2,
   "unit_price": 45}, {…Router…}],
 "tax": 37.80, "total": 247.80}

Enums and nulls

Two schema features do a lot of work. Enums turn free text into a fixed set of labels, so you never have to map U S dollars, the dollar sign and lowercase usd to one code. Required fields guarantee every key is present. But what if the invoice has no purchase order number? If the field must be a string, the model will invent one that looks right. Make it string or null, and say: null if not printed. Give the model an honest way to say it found nothing.

Two features that matter
  • enums currency: one of 3 codes never "US Dollars", "$", "usd"
  • required + nullable po_number: string or null "null if not printed on the invoice"
  • no null option → the model
  • invents a plausible value

Small and flat

Keep schemas small and flat. Deep nesting and hundreds of fields make the model's job harder and can exceed the limits providers put on enforced schemas. Split a big extraction into two calls instead. Not every JSON Schema keyword is enforced everywhere, so check whether pattern, format or minimum really are. And the model writes keys in order. If you want a short justification, put it before the verdict, so the verdict is written after the evidence.

Schema design
  • flat beats deeply nested
  • tens of fields, not hundreds: split big jobs into 2 calls
  • short, clear key names
  • not every keyword is enforced everywhere: check pattern, format, minimum, maxLength
  • keys are written in order: evidence before the verdict

Valid is not correct

Now the most important rule. Constrained decoding guarantees the shape, never the truth. Say the model returns a total of two hundred and seventy four eighty. That is a valid number, so the schema passes. But your validator adds ninety, plus a hundred and twenty, plus thirty seven eighty tax, gets two hundred and forty seven eighty, and rejects it. Check types, ranges and business rules in code: sane dates, positive quantities, known vendors, totals that add up.

Schema-valid, still wrong
{"total": 274.80, ...}   type: ok

checks a schema cannot do:
  2x45 + 1x120 + 37.80 = 247.80
  247.80 ≠ 274.80  → reject
  date not in the future
  qty > 0, prices > 0
  vendor is a known supplier
  currency matches that vendor

Validate and retry

When validation fails, retry with the error. Send the same document plus a specific message: total is two seventy four eighty, but items plus tax come to two forty seven eighty, re read the totals line. Specific errors get fixed far more often than a bare try again. Cap it at two retries. If it still fails, send the invoice to a review queue rather than saving a guess. Every retry is a full model call, so track the retry rate as a quality signal.

The retry loop
for attempt in 1..3:
  out = model(doc, errors)
  problems = validate(out)
  if not problems:
    return save(out)
  errors = problems
send_to_review(doc, out)

error: "total is 274.80 but items
  + tax = 247.80. Re-read the
  totals line of the invoice."

Forcing a tool call

There is a second route to structure. Define a tool called record invoice whose input schema is your invoice schema, and set tool choice so the model must call exactly that tool. You never run it. You just read the arguments, which are your extracted fields. This works where there is no dedicated structured output mode, and fits agents that already use tools. With strict tool mode turned on, the arguments are constrained to the schema too.

Structure through tools
  • define a tool record_invoice
  • whose input schema is the invoice schema
  • set tool choice to that tool: the model must call it
  • you never run it. The arguments are your output
  • strict tools: schema enforced

Streaming partial JSON

Long outputs can be streamed, so users see fields fill in as they are written. Chunks split anywhere, even mid key, so a normal JSON parser fails until the very end. A partial JSON parser closes the open strings and brackets to give a best guess so far. Use that for display only. A quantity of two may still become twenty five on the next chunk. Save, charge or trigger anything only from the final, complete object, after it passes validation.

Streaming partial JSON
chunk 1  {"vendor": "Ac
chunk 2  me Ltd", "items": [{"de
chunk 3  sc": "Cable kit", "qty": 2

a partial parser closes the open
strings and brackets for display:
  vendor "Acme Ltd", desc "Cable
  kit", qty 2  (may become 25!)

render early; act only on the
final, complete, validated object

Common mistakes

The usual mistakes. Trusting values just because the JSON parsed. No null option, so missing fields get confident guesses. Regular expressions to strip code fences when strict mode is available. Ignoring the stop reason. Even with constrained decoding, a reply that hits the max token limit is cut off mid object, and a refusal may not match your schema, so check why the reply ended before parsing. And one giant nested schema doing ten jobs.

Common mistakes
  • trusting values because the JSON parsed
  • no null option, so gaps get filled with guesses
  • regex to strip code fences instead of strict mode
  • ignoring the stop reason: max tokens = truncated JSON
  • one giant nested schema
  • acting on streamed partials

Numbers worth knowing

Some ballparks. Prompt only JSON fails rarely, but one in a thousand times a million calls a day is about a thousand bad records daily. Schema enforced output brings parse failures to about zero, apart from truncation and refusals. The first request with a new schema can be slower while its grammar is compiled, and later ones reuse it. Cap retries at about two. And since output tokens cost three to five times input, long key names add up at scale.

Ballpark numbers
prompt-only parse failures: rare,
  but 0.1% of 1M calls a day
  = ~1,000 bad records a day
schema-enforced parse fails  ~0
  (except truncation, refusals)
first call, new schema   can be
  slower: grammar is compiled
retries per item         ≤ 2
each retry               full call
output vs input          ~3-5x price
long keys, padding       cost tokens

Say it like this

How to say it. We extract invoices with schema enforced output: a small, flat JSON Schema with enums for currency and nullable fields for anything optional. Constrained decoding guarantees the shape. Our validator then checks the values: totals add up, dates are sane, the vendor exists. Failures retry up to twice with a specific error, then go to a review queue. Shape is guaranteed, values are validated. That line shows you have shipped this.

In the interview
  • "We extract invoices with a small, flat JSON Schema in strict mode: enums for currency, nullable optional fields. The decoder guarantees the shape; our validator checks totals, dates and vendors. Failures retry twice with the error, then go to a review queue."

Interview questions

Q1What is the difference between JSON mode and schema-enforced structured output?

JSON mode guarantees the reply parses as JSON but not which keys or types it has. Schema-enforced output takes a JSON Schema and guarantees the reply matches it, with required fields, types and enums all respected.

Q2How does constrained decoding work?

The schema is compiled into a grammar or state machine. At each generation step the model scores all tokens as usual, then every token that would make the output invalid is masked to zero probability and the rest are renormalised before sampling, so the result always fits the grammar.

Q3If the output matches the schema, can you trust it?

No. The schema guarantees shape, not truth. Validate values in code: ranges, dates, cross-field rules such as line items plus tax equal the total, and lookups such as the vendor existing. Reject or retry when a rule fails.

Q4How do you handle a field that may be missing from the source document?

Make it required but nullable, and tell the model to return null when the value is not present. Without a null option the model tends to invent a plausible value to satisfy the schema.

Q5What should a retry loop for structured output look like?

Validate the output, and on failure call the model again with the same input plus a specific error message describing what was wrong. Cap retries at around two, then route the item to human review instead of saving a guess.

Q6Why keep schemas small and flat?

Large, deeply nested schemas are followed less reliably, cost more tokens, and can exceed provider limits on enforced schemas. Splitting a big extraction into smaller calls and using short, clear keys and descriptions works better.

Q7How can tool calling be used to get structured output?

Define a tool whose input schema is the data you want, force the model to call that specific tool, and read the arguments as your output without running anything. With strict tool mode, the arguments are schema-enforced too.

Q8How do you stream structured output safely?

Use a partial JSON parser that closes open strings and brackets so you can render fields as they arrive, but treat those values as provisional. Only act on the final complete object after checking the stop reason and validating it.