esc
  • WorkflowsPages
  • Case studiesPages
  • Machine Learning FoundationsLearn
  • AI EngineeringLearn
  • AI Guardrails & Red TeamingLearn
  • UI/UXLearn
  • Design SystemsLearn
  • Production System DesignLearn
  • AI papersPages
  • Interview KitPages
  • Book a callContact
  • Download ResumeContact
Let’s talk

I’ll build the agent for it.

How Do You Get Reliable JSON Output?

Why models break JSON, how schema mode and code checks fix it, and what to say about it, for your AI interview.

In short

Use the model's structured output mode with a JSON Schema, so it can only write your fields and types. Then still parse, validate and check business rules in your code, because a schema can't catch everything.

12 min readIntermediateVery common · estimateFacts checked 26 November 2026

Say it out loud

Read it once, then say it without looking. Start with the short one; use the long one when they ask you to go deeper.

Asking a model for JSON in the prompt gets you JSON most of the time, and most of the time is not enough. My fix has two parts. First, I use the vendor's structured output mode with a JSON schema, so the model can only write the fields and types I asked for. Second, I still parse and validate the reply in my code and check the business rules, because a schema can't catch a refusal, a cut-off reply or a claim that needs a person to check it. Failures get one retry, then a person.

What is reliable JSON output, in plain words?

JSON is a plain text format for data. Each piece has a name and a value, the whole thing sits in curly braces, and every quote and comma has to be in the right place. Programs read it, but a model writes it as text, one piece at a time, so it can break those rules.

Reliable output means three things, and each can fail on its own. The reply parses, so the syntax is right. The reply has the shape you asked for, so the fields exist and hold the right types. And the values make sense for the business, such as an amount below your limit.

Think of a claims clerk at an insurer who types a handwritten form into the system. A form with fixed boxes stops a date going missing. A second check against the policy catches the rest. An AI agent needs both: a fixed shape for the reply, and a check on what the reply says.

Here is the real case. A claims triage agent reads a customer's email and returns the claim as JSON for the payments system. If the amount comes back as text, or a claim skips its check, real money moves.

Key words

JSON
A text format for data: named fields in curly braces, read by almost every program.
Schema
A written description of the fields: their names, their types, and which ones are required.
Refusal
The model declines to answer, often for safety reasons. The reply then carries a refusal message in place of your data.
Validation
Checking data against your rules before any system uses it.
Parse
Reading text and turning it into data your program can use, or failing if the text is broken.

What are the ways to get JSON out of a model?

There are three approaches, from the weakest to the strongest.

  • Weakest

    Ask nicely

    Add a line to the prompt asking for JSON, then parse what comes back. A code fence, some chatty text, a trailing comma or a string where a number belongs can all break it.

  • Better

    Schema mode

    Send your JSON schema with the request. The output is limited to your fields and types, so the format is right by design.

  • Best for tool calls

    Strict tool arguments

    When the model asks to use one of your functions (a tool your code runs), strict tool use checks the tool name and its inputs against the schema.

Schema mode is the first thing to reach for. OpenAI calls it Structured Outputs, and Anthropic calls it structured outputs with a JSON schema. The two vendors describe the same idea in their own words.

  • “Structured Outputs constrains completed, non-refusal model output to your supplied JSON Schema.”

    OpenAI

  • “Structured outputs guarantee schema-compliant responses through constrained decoding”

    Anthropic

Anthropic calls the mechanism constrained decoding. The model can only pick the next piece of text that fits your schema, so a finished reply is far less likely to drift off the shape. Anthropic's own docs say the output can still be incomplete and not match the schema, so the code checks stay. OpenAI also says plain JSON mode only makes sure the output is valid JSON, while Structured Outputs also makes sure it follows your schema.

Schema mode: the reply follows your schema

Your JSON Schema

field names, types, required

Model

writes only what the schema allows

JSON in shape

parses, with the right fields

  1. 1Your schema travels with the request, so the vendor knows the shape you want.
  2. 2The model's output is limited to that shape, so the reply comes back in shape.
With schema mode, the schema travels with the request and limits what the model can write. Refusals and replies that stop early can still come back, so the code checks stay.

Tip

Anthropic says the first call with a new schema is slower, while the schema is prepared. Run each new schema once in a test before it meets live traffic.

What must your code still check?

A schema covers the shape of the reply. It can't see your business rules, and it can't stop a refusal or a reply that stops early.

  • “Your application still needs to handle refusals, incomplete responses, and API errors, and validate any business rules that the schema does not express.”

    OpenAI

  • “The output might be incomplete and not match your schema.”

    Anthropic

So the reply still goes through checks, in a fixed order. Parse it. Check the fields and types. Check the business rules. Each check is cheap, and each one catches a different kind of failure.

Checks in your code, after the model replies

Model reply

text that should be JSON

Your code checks, in order

Is it JSON?

a refusal or cut-off reply fails here

Right fields and types?

numbers stay numbers

Business rules pass?

limits, known IDs, dates

Retry once

one more try, then a person

Use the result

passes every check

  1. 1The reply from the model arrives at your code.
  2. 2A reply that reads as JSON moves on to the field and type check.
  3. 3A reply with the right fields moves on to the business rules.
  4. 4A reply that passes every check is used.
  5. 5Any failed check sends the error back once. A second failure goes to a person.
Your code checks the reply in order: parse, fields and types, then business rules. A reply that fails any check gets one retry with the error sent back, then goes to a person. Schema mode does not replace these checks.

Here is a small worked example. A claims triage agent asks the model for one claim as JSON. The three replies in the script are the kind a model can send. No model runs here, so the output is the same every time you run it.

Python
# A claims triage agent asks the model for one claim as JSON.
# The model is not run here; these are three replies it might send.
import json

REQUIRED = {"claim_id": str, "amount_gbp": (int, float), "needs_human": bool}

def check(raw):
    try:
        data = json.loads(raw)  # parse: is it JSON at all?
    except json.JSONDecodeError as err:
        return None, "not valid JSON: " + err.msg
    for key, kind in REQUIRED.items():  # shape: right fields, right types
        if not isinstance(data.get(key), kind):
            return None, "field " + key + " missing or wrong type"
    if data["amount_gbp"] > 50000:  # over the limit: send to a person, not just reject
        return None, "amount over the 50,000 limit, send to a person"
    return data, "ok"

replies = [
    '{"claim_id": "C-1042", "amount_gbp": 1200, "needs_human": false,}',
    '{"claim_id": "C-1042", "amount_gbp": "1,200", "needs_human": false}',
    '{"claim_id": "C-1042", "amount_gbp": 1200, "needs_human": false}',
]
for attempt, raw in enumerate(replies, 1):
    data, message = check(raw)
    print("attempt " + str(attempt) + ": " + message)
    if data:
        print("accepted claim " + data["claim_id"])
        break

Output

attempt 1: not valid JSON: Illegal trailing comma before end of object
attempt 2: field amount_gbp missing or wrong type
attempt 3: ok
accepted claim C-1042

Attempt 1 has a trailing comma, so it fails the parse. Attempt 2 has the amount as text, so it fails the type check. Attempt 3 passes and the claim goes on. A claim over 50,000 pounds would be stopped too. Anthropic's schema mode does not support numerical constraints such as maximum, so this check has to live in your code.

Tip

Anthropic warns that enum values (a fixed list of allowed answers) can come back with a different capital letter. Compare them without caring about case, or map them to your own codes in code.

How would you make this reliable in production?

Walk through it in order, so the interviewer hears the whole system, not just a prompt trick.

  1. 1

    Write the schema

    Name the fields, their types and the required ones. Anthropic says objects must set additionalProperties to false, and it supports the required keyword. That means no extra fields are allowed.

  2. 2

    Turn on schema mode

    Send the schema with every request. Use strict tool arguments for the functions where a wrong input does real harm. Anthropic advises marking only critical tools as strict.

  3. 3

    Check in code

    Parse the reply, check the fields and types, then the business rules. A reply that looks right still gets checked.

  4. 4

    Retry once, with the error

    Send the exact error back so the model can fix that one thing. Keep it to one retry, so a bad case cannot loop.

  5. 5

    Send the rest to a person

    Claims over the limit, and anything that fails twice, go to a claims handler with the original email attached.

  6. 6

    Test with bad replies

    Keep a set of broken replies and odd claims, run it on every change, and count the failures in your logs.

What does the interviewer want to hear?

A strong answer covers

  • Schema mode first, named as the vendor's own feature.
  • Why a prompt alone is not enough: the format is a request, not a rule.
  • Code checks after the reply: parse, fields and types, business rules.
  • Refusals and cut-off replies still need handling.
  • One retry with the error, then a person, with a limit on both.
  • An honest line: valid JSON can still hold a wrong value.

Common traps

  • Trap"Just tell the model to return JSON."

    BetterA prompt line is only a request. Use schema mode, then check the reply in code.

  • Trap"If it's valid JSON, it's correct."

    BetterValid JSON can still hold the wrong amount. Business rules are a separate check.

  • Trap"Keep retrying until it works."

    BetterLimit retries to one, send the error back, and route the rest to a person.

Can you spot the problem?

Spot the reply for a person

Your claims agent checks four replies. Which one passes the format check but must still go to a person?

Quick check

A model keeps adding a code fence and a stray comma to its JSON. What is the strongest fix?

Can you answer these from memory?

Flash cards · tap a card to flip it

1 / 6

What will they ask next?

  1. Q086JSON mode vs strict schema structured outputs?10 min
  2. Q178What is parallel tool calling?Coming soon
  3. Q448How do you extract structured data from documents and images?Coming soon
  4. Q201What is prompt injection?12 min

Learn it in depth

Last updated on 26 November 2026

Building an agent that returns data your systems must trust?

I design and build AI agents with schema-checked outputs, checks in code and a clear path to a person. Book a short call and tell me what your agent needs to return.