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.
11 min readBeginnerCommon · estimateFacts checked 27 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.
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.
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.
Key words
- 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.
The parse, check and retry loop
Ask the model
one JSON object back
Check the reply
Parse as JSON
can it be read at all?
Check the fields
names, types, allowed values
Use the data
passes every check
Send the error back
then ask again, a few times
- 1The model's reply comes back as text.
- 2Valid JSON moves on to the field checks.
- 3Every field passes, so the data is used.
- 4A field is missing or has the wrong value.
- 5The text cannot be read as JSON, so it fails here.
- 6The 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.
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
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."
BetterSame prompt, same mistake. Send the exact error back, and set a limit.
Trap"JSON mode means I never need to parse it."
BetterStill parse and check it. The schema, the stop reason and the business rules are your code's job.
Trap"Keep retrying until it works."
BetterSet 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?
Quick check
A reply stops halfway, and its stop reason is max_tokens. What is the right first step?
Can you answer these from memory?
Flash cards · tap a card to flip it
What will they ask next?
- Q085How do you get reliable JSON output?12 min
- Q086JSON mode vs strict schema structured outputs?10 min
- Q176How should an agent handle tool errors and retries?14 min
- Q205Input vs output guardrails?11 min
- Q173How do you stop endless agent loops?11 min
- Q448How do you extract structured data from documents and images?12 min
Learn it in depth
Last updated on 27 November 2026
Building an agent whose output your systems must accept?
I design and build AI agents with these checks in place: strict schemas, stop-reason handling, retry limits and a human fallback. Book a short call and tell me what your system needs to accept.