By Abhijith N M · Reviewed 24 October 2026 · Editorial standards
You asked for JSON. You got:
Sure! Here is the evaluation you requested:
```json
{"score": 0.8, "reason": "The answer is mostly supported by the context."}
```
Let me know if you need anything else!That is a perfectly reasonable reply and a json.loads() crash. Every AI testing codebase needs a small, boring, defensive parser. Write it once and reuse it everywhere.
import json, re
def extract_json(text: str) -> dict:
"""Pull the first JSON object out of a model reply, or raise ValueError."""
# 1. Try the whole string (ideal case, JSON mode)
try:
value = json.loads(text)
if isinstance(value, dict):
return value
except json.JSONDecodeError:
pass
# 2. Try fenced blocks: ```json { ... } ```
fenced = re.search(r"```(?:json)?\s*(\{.*?\})\s*```", text, re.S)
if fenced:
try:
return json.loads(fenced.group(1))
except json.JSONDecodeError:
pass
# 3. Try the first {...} that balances
start = text.find("{")
while start != -1:
depth = 0
for i in range(start, len(text)):
depth += {"{": 1, "}": -1}.get(text[i], 0)
if depth == 0:
try:
return json.loads(text[start:i+1])
except json.JSONDecodeError:
break
start = text.find("{", start + 1)
raise ValueError("no JSON object found in model reply")Valid JSON can still be wrong. {"score": "high"} parses fine and breaks your maths. Validate types and ranges before you trust a score:
def validate_eval(obj: dict) -> dict:
score = obj.get("score")
if not isinstance(score, (int, float)):
raise ValueError(f"score must be numeric, got {type(score).__name__}")
if not 0.0 <= float(score) <= 1.0:
raise ValueError(f"score out of range: {score}")
reason = obj.get("reason")
if not isinstance(reason, str) or not reason.strip():
raise ValueError("reason must be a non-empty string")
return {"score": float(score), "reason": reason.strip()}A cheap and effective pattern: if the judge's reply cannot be parsed, send it back with 'your previous reply was not valid JSON; return only the object'. One retry recovers most cases. Two retries almost never help and double the cost.
Call the judge with JSON mode enabled and a schema in the prompt.
Parse with extract_json, then validate with validate_eval.
On failure, retry once with the malformed reply and the instruction restated.
On the second failure, record the case as a harness failure — do not silently assign 0.0.
Key takeaways
Models return JSON wrapped in prose and fences — write a defensive extractor.
Validate types and ranges, not just syntax.
Retry once with feedback on a parse failure; never more.
Never default a failed parse to 0.0 — mark it errored.
Written and edited by the nexGenCoders team. Spotted a mistake? Tell us and we will fix it.
Don't lose this lesson
Create a free account to save your progress, keep your streak, and work toward a shareable certificate.