# Parse and Validate LLM JSON, Retrying on Failure

> How to read a model's JSON reply safely, check every field, and retry with the error, for your AI interview.

**In short:** Ask the model for JSON, parse it with a real parser, check every field in your own code, and if it fails, send the exact error back and try again a few times. If it still fails, hand the case to a person instead of guessing.

AI and LLM interview question Q478, Coding and practical. Beginner, common (our estimate). From Venkat R. Murty's free Interview Kit: https://designervenkat.online/interview/ai/parse-and-validate-llm-json-retrying-on-failure

## Say it in 30 seconds

A model's JSON can be cut off, wrapped in chatty text, or have a field in the wrong case, so I never trust it straight away. My code parses it, checks each field, and if something fails, it sends the exact error back and tries again, three tries at most. If it still fails, the case goes to a person. The model writes the reply. My code decides whether it's usable.

## Say it in 2 minutes

Our claims triage agent asks the model for one JSON object per insurance claim. It holds a claim ID, a category, an amount and a flag for a person to check. The model is good at this, but it writes text, and text can break. A reply can stop halfway when it hits the length limit, start with a friendly sentence, or return Auto where our schema says auto. Any of those would break the claims system if we passed them on.

So the code works in order. First it checks the stop reason, so a refusal or a cut-off reply gets its own path. Then it reads the text as JSON with a real parser, checks the fields, and finally checks the business rules, such as an amount that can't be negative. A schema can't express that last rule, so the code has to.

If a check fails, the loop sends the exact error back with the next question and asks again, three tries at most. Retrying the same prompt blindly wastes money and often gives the same mistake. When the tries run out, the claim goes to a person. The model never gets the final say on whether a claim is fine.

## What is parsing and validating JSON, in plain words?

An AI model writes its reply one piece of text at a time. When you ask it for JSON, a data format of named fields and values, it usually writes valid JSON. Nothing forces it to, though, so your code has to read the reply and check it.

Parsing means reading that text as data your code can use. Validating means checking the data has the shape you expected: the right fields, the right types, and values from an allowed list.

Think of a bank's back office keying in loan forms from branches. A form must be readable and every box filled in correctly. A form with a missing signature goes back to the branch and never reaches the ledger. A claims agent works the same way: the claims system accepts only a reply that passes the checks.

- **JSON:** A plain text format for data: named fields with values, written in curly braces.
- **Schema:** The written rules a JSON object must follow: field names, types and allowed values.
- **Parse:** Read text and turn it into data your code can use.
- **Retry:** Ask again after a failure, with a limit, and with what went wrong.
- **Stop reason:** The label a reply carries that says why the model stopped, such as a finished answer, a length limit or a refusal.

## Why does a model's JSON come back wrong?

Three things go wrong, and each needs its own fix. Only the last one gives valid JSON with the wrong data.

- **Cut off: Hit the length limit.** The reply stops mid-object, so a closing brace or a field is missing. Retry with a higher limit.
- **Refused: The model said no.** The model refused for safety reasons. Its stop reason says so, and the output might not match your schema. Send it to a person.
- **Wrong shape: Valid JSON, wrong data.** A missing field, text where a number belongs, or Auto where the schema says auto.

Anthropic's structured output mode, a setting that makes the model follow your schema, is described as "Always valid: No JSON parsing errors". Its docs still list the cases where a reply can miss the schema, and OpenAI makes the same point.

> "Your application still needs to handle refusals, incomplete responses, and API errors, and validate any business rules that the schema does not express." (OpenAI, Structured Outputs guide)
>
> "Always valid: No JSON parsing errors" (Anthropic, structured outputs guide)

Capital letters are a classic trap. Anthropic's docs warn that capitals in a fixed list of allowed values (called an enum) are not guaranteed. A value may differ from the schema only in capitals, so Auto can come back where auto was asked for. The docs advise comparing enum values without caring about capitals.

> **Tip:** Asked whether structured output removes the need for checks? Say it lowers the errors. Your code still checks the stop reason, the schema and the business rules.

## How do you parse and validate a reply, step by step?

1. **Check the stop reason:** Refusal or cut off? Handle it first, because each needs a different fix from a wrong field.
2. **Parse the text:** Read it with a real JSON parser. In Python's json module, a document that isn't valid JSON raises JSONDecodeError, an error you can catch.
3. **Check the shape:** Look at field names, types and allowed values. Keep the list of allowed values in one place.
4. **Check the business rules:** An amount under the claim limit, a date not in the future, a policy that exists. A schema can't express these.

*Diagram, The parse, check and retry loop: A reply must pass the parse and field checks. A failed check goes back to the model with the error, up to a small limit, and then the case goes to a person. The stop-reason check runs before this loop, and the business-rule check after it.*
1. The model's reply comes back as text.
2. Valid JSON moves on to the field checks.
3. Every field passes, so the data is used.
4. A field is missing or has the wrong value.
5. The text cannot be read as JSON, so it fails here.
6. The error goes back with the question, and the model tries again.

Here is the core loop in 30 lines of plain Python. It skips the stop-reason and business-rule checks to stay short. A fake model sends two bad replies and then a good one, so you can see each retry.

```python
import json

def check(data):
    if not isinstance(data, dict): return ["not a JSON object"]
    problems = []
    if data.get("category") not in ("auto", "home", "health"):
        problems.append("category must be auto, home or health")
    if not isinstance(data.get("amount_usd"), (int, float)):
        problems.append("amount_usd must be a number")
    return problems

def triage(ask_model, max_tries=3):
    feedback = ""
    for attempt in range(1, max_tries + 1):
        try:
            data = json.loads(ask_model(feedback))
            problems = check(data)
        except json.JSONDecodeError as err:
            problems = ["not valid JSON: " + err.msg]
        if not problems:
            return data
        feedback = "; ".join(problems)
        print("try", attempt, "failed:", feedback)
    return None  # a person takes over
replies = iter([  # made-up replies; the fake model ignores the feedback
    '{"claim_id": "C-1042", "category": "auto"',
    '{"claim_id": "C-1042", "category": "Auto", "amount_usd": 1830.5}',
    '{"claim_id": "C-1042", "category": "auto", "amount_usd": 1830.5}',
])
print(triage(lambda feedback: next(replies)))
```

Output:

```text
try 1 failed: not valid JSON: Expecting ',' delimiter
try 2 failed: category must be auto, home or health
{'claim_id': 'C-1042', 'category': 'auto', 'amount_usd': 1830.5}
```

The first reply is cut off, so the parser fails. The second has Auto, so the field check fails. The third passes, and the data is used.

## How do you retry without looping forever?

There are two kinds of retry, and interviewers like to hear you separate them. An API error (a failure from the model service itself, such as a timeout or a rate limit) is retried with backoff, which means waiting longer after each failure, and with a limit. Bad JSON is different. Sending the same prompt again often gets the same mistake, so the retry has to carry the error message.

> "Without the SDK, follow x-should-retry and retry-after in your own code and use backoff and a retry limit." (Anthropic, API errors)

- **Send the exact error back:** Name the missing field or the wrong value, so the model knows what to fix.
- **Cap the tries:** Three is a common small number. After it, hand the case to a person.
- **Log every bad reply:** Keep the stop reason and the error, so you can see which failures are growing.
- **Never store a failed reply as good:** A bad reply is not data. Only a reply that passes every check gets saved.

> **Tip:** Asked how you'd stop endless retries? Say a small cap, a fallback to a person, and a log that shows the failure rate. Each retry is another paid call.

### How would you run this for 40,000 claims a day?

Start with a test set of saved bad replies, with names removed, taken from real failures. Run every new prompt or model version against that set before it ships.

- **Watch the retry rate:** Track it per prompt version, and alert the team when it jumps.
- **Keep one schema:** The prompt and the checker both read the same schema file, so they can't drift apart.
- **Set a retry budget:** One broken prompt must not multiply the bill across every claim.
- **Queue the fallbacks:** Cases that end with a person go to a review queue with the bad replies attached.

## What does the interviewer want to hear?

**A strong answer covers**

- [ ] Parse first, then check the shape, then check the business rules.
- [ ] Structured output lowers the errors, but your code still checks the reply.
- [ ] Stop reason before JSON: refusals and cut-off replies need their own fix.
- [ ] Retry with the exact error, a small limit, and a person at the end.
- [ ] API retries use backoff. Bad-content retries send the error back.
- [ ] Tests on saved bad replies, and a retry-rate alert, so you see it getting worse.

**Common traps**

- Trap: "Just call the model again with the same prompt." Better: Same prompt, same mistake. Send the exact error back, and set a limit.
- Trap: "JSON mode means I never need to parse it." Better: Still parse and check it. The schema, the stop reason and the business rules are your code's job.
- Trap: "Keep retrying until it works." Better: Set a small limit, then send the case to a person. Endless retries cost money and hide the bug.

## Can you spot the danger?

**Spot the danger:** This claims step pays out whatever the model sent. Which snippet is the danger?

A. except json.JSONDecodeError as err: retry with the error text
B. if stop_reason == 'refusal': send to a person
C. amount = data['amount_usd']; pay_claim(amount)
D. for attempt in range(1, 4): ask the model again

**Answer:** C. The payout uses the model's number with no type or limit check. Check the amount first, and treat a refusal or a cut-off reply as its own case. The retry loop on the last option is weak too, since it sends no error back, but it pays nothing out.

**Quick check:** A reply stops halfway, and its stop reason is max_tokens. What is the right first step?

A. Send the same prompt again, unchanged
B. Raise the length limit and retry
C. Ask the model to apologise and rewrite it
D. Lower the temperature and parse again

**Answer:** B. A cut-off reply is incomplete, so a stricter prompt can't add the missing text. Anthropic's docs say to retry with a higher max_tokens value.

## Can you answer these from memory?

**Flash cards**

- **What does parsing mean?** Reading text as JSON, so your code gets structured data.
- **What does validating mean?** Checking fields, types, allowed values and business rules.
- **Why check the stop reason first?** Refusals and cut-off replies need their own fix: a person for a refusal, a higher limit for a cut-off.
- **What does a retry send back?** The exact error, so the model knows what to fix.
- **What happens after the last retry?** The case goes to a person. It is never saved as good.
- **API retry vs content retry?** API errors use backoff and a limit. Bad JSON gets the error sent back.

## Likely follow-up questions

- Q085 How do you get reliable JSON output? https://designervenkat.online/interview/ai/how-to-get-reliable-json-from-an-llm
- Q086 JSON mode vs strict schema structured outputs? https://designervenkat.online/interview/ai/json-mode-vs-strict-schema-structured-outputs
- Q176 How should an agent handle tool errors and retries? https://designervenkat.online/interview/ai/how-should-an-agent-handle-tool-errors-and-retries
- Q205 Input vs output guardrails? https://designervenkat.online/interview/ai/input-vs-output-guardrails
- Q173 How do you stop endless agent loops? https://designervenkat.online/interview/ai/how-do-you-stop-endless-agent-loops
- Q448 How do you extract structured data from documents and images? https://designervenkat.online/interview/ai/extract-structured-data-from-documents-and-images

## Learn it in depth

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