# 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.

AI and LLM interview question Q085, Prompt and context engineering. Intermediate, very common (our estimate). From Venkat R. Murty's free Interview Kit: https://designervenkat.online/interview/ai/how-to-get-reliable-json-from-an-llm

## Say it in 30 seconds

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.

## Say it in 2 minutes

A language model writes text one piece at a time, so it can slip in a stray comma, wrap the answer in a code fence or leave out a field. If I only ask for JSON in the prompt, I get valid JSON most of the time. That is the problem: in a claims system, one bad reply in a hundred is still a bad claim.

The first fix is schema mode. I send the vendor my JSON schema with the request, and the model's output is limited to that shape. OpenAI and Anthropic both offer this. It fixes the format and the types, but not everything. A refusal or a reply that stops early can still come back, and a schema can't send a claim over 50,000 pounds to a person.

So my code still does real work. It parses the reply, checks the fields and types, then checks the business rules. If a check fails, the error goes back to the model once. If the second try fails too, a person takes the claim. I keep those approvals rare, so people actually read them.

Interviewers want three things: the schema, the code checks, and an honest line that a schema is not a guarantee of correct content. The last point matters most. Valid JSON can still hold the wrong amount.

## 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.

- **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.

*Diagram, Schema mode: the reply follows your schema: 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.*
1. Your schema travels with the request, so the vendor knows the shape you want.
2. The model's output is limited to that shape, so the reply comes back in shape.

> **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.

*Diagram, Checks in your code, after the model replies: 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.*
1. The reply from the model arrives at your code.
2. A reply that reads as JSON moves on to the field and type check.
3. A reply with the right fields moves on to the business rules.
4. A reply that passes every check is used.
5. Any failed check sends the error back once. A second failure goes to a person.

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:

```text
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. **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. **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. **Check in code:** Parse the reply, check the fields and types, then the business rules. A reply that looks right still gets checked.
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. **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. **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." Better: A prompt line is only a request. Use schema mode, then check the reply in code.
- Trap: "If it's valid JSON, it's correct." Better: Valid JSON can still hold the wrong amount. Business rules are a separate check.
- Trap: "Keep retrying until it works." Better: Limit 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?

A. {"claim_id": "C-2281", "amount_gbp": "480", "needs_human": false}
B. {"claim_id": "C-2281", "amount_gbp": 480, "needs_human": false
C. {"claim_id": "C-2281", "amount_gbp": 68000, "needs_human": false}
D. {"claim_id": "C-2281", "amount_gbp": 480, "needs_human": "no"}

**Answer:** C. Every field is there and the amount is a number, so the format passes. 68,000 pounds is over the 50,000 limit, so a business rule sends it to a person. The other three fail the format check: a text amount, a missing closing brace, and a text answer where true or false belongs.

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

A. Add a line to the prompt asking for careful JSON
B. Turn on schema mode, and keep the parse check in code
C. Switch to a bigger model
D. Lower the temperature (how random the replies are)

**Answer:** B. Schema mode limits what the model can write, so the format is right by design. Keep the parse check anyway, because refusals and replies that stop early still reach your code. A prompt line, a bigger model or a lower temperature (a setting for how random the replies are) can make errors less likely, but none of them sets the format.

## Can you answer these from memory?

**Flash cards**

- **What is the strongest fix for format errors?** Schema mode: the vendor limits the output to your JSON Schema.
- **Does a schema check business rules?** Not your business rules. Your code checks who approves, known IDs and dates after the parse.
- **What still breaks with schema mode?** Refusals and replies that stop early. Handle them in code.
- **Why does a prompt-only fix fail?** It is a request, not a rule, so stray text and wrong types still slip in.
- **What does a retry send back?** The exact error, so the model can fix that one thing. Only once.
- **When does a person take over?** When the retry fails too, or a rule says a person must check.

## Likely follow-up questions

- Q086 JSON mode vs strict schema structured outputs? https://designervenkat.online/interview/ai/json-mode-vs-strict-schema-structured-outputs
- Q178 What is parallel tool calling? (full answer coming)
- Q448 How do you extract structured data from documents and images? (full answer coming)
- Q201 What is prompt injection? https://designervenkat.online/interview/ai/what-is-prompt-injection

## Learn it in depth

- [Structured Output](https://designervenkat.online/learn/ai-engineering/structured-output)
- [Function Calling](https://designervenkat.online/learn/ai-engineering/function-calling)
