LLM API JSON Mode: Common Pitfalls and Reliable Validation
Summary
I dissect common JSON mode LLM API issues and show how to build a reliable pipeline: schema, validation, retries, and parsing invalid output.
Why Use JSON Mode
JSON mode forces the model to return valid JSON, but it does not guarantee schema compliance. The model may omit fields, return null instead of an array, or use an incorrect type. I view JSON mode as a first approximation, not a final guarantee.
Typical Failures
| Problem | Example | Cause |
|---|---|---|
| Extra text before JSON | Here is the response: {"key": "value"} |
The model added an explanation |
| Missing fields | {"name": "x"} instead of {"name": "x", "age": 30} |
The schema is not followed |
| Incorrect type | {"count": "5"} instead of {"count": 5} |
The model returned a string |
| Nested quotes | {"text": "He said "hello""} |
Escaping is broken |
| Empty response | {} |
The model did not find data |
Request Configuration
I pass the schema in the response_format parameter and duplicate it in the system prompt. This increases the likelihood of accurate compliance.
import json
from openai import OpenAI
client = OpenAI()
schema = {
"type": "object",
"properties": {
"title": {"type": "string"},
"price": {"type": "number"},
"in_stock": {"type": "boolean"},
"tags": {"type": "array", "items": {"type": "string"}}
},
"required": ["title", "price", "in_stock", "tags"]
}
response = client.chat.completions.create(
model="gpt-4o-mini",
response_format={"type": "json_object"},
messages=[
{"role": "system", "content": f"Return JSON according to the schema: {json.dumps(schema)}"},
{"role": "user", "content": "Describe the product: laptop for 75000 rubles, in stock, tags: electronics, work"}
]
)
raw = response.choices[0].message.content
print(raw)
Schema Validation
I use the jsonschema library for strict validation. This catches errors before they reach the business logic.
from jsonschema import validate, ValidationError
def validate_json(raw: str, schema: dict) -> dict:
try:
data = json.loads(raw)
except json.JSONDecodeError as e:
raise ValueError(f"Invalid JSON: {e}")
try:
validate(instance=data, schema=schema)
except ValidationError as e:
raise ValueError(f"Schema violated: {e.message}")
return data
try:
product = validate_json(raw, schema)
print(product["title"])
except ValueError as e:
print(f"Error: {e}")
Retrying with Corrections
If validation fails, I send the model a message with the error and ask it to fix it. This is cheaper than a new request from scratch.
def request_with_retry(messages: list, schema: dict, max_retries: int = 3):
for attempt in range(max_retries):
response = client.chat.completions.create(
model="gpt-4o-mini",
response_format={"type": "json_object"},
messages=messages
)
raw = response.choices[0].message.content
try:
return validate_json(raw, schema)
except ValueError as e:
if attempt == max_retries - 1:
raise
# Add error message
messages.append({"role": "assistant", "content": raw})
messages.append({"role": "user", "content": f"Error: {e}. Fix the JSON."})
raise RuntimeError("Could not get valid JSON")
Extracting JSON from Dirty Output
Some providers do not support JSON mode. Then I extract JSON from the text using a regular expression and try to repair damaged parts.
import re
def extract_json(text: str) -> str:
# Find the first JSON object
match = re.search(r'\{.*\}', text, re.DOTALL)
if not match:
raise ValueError("JSON not found in response")
return match.group(0)
def repair_json(raw: str) -> dict:
# Remove trailing commas
raw = re.sub(r',\s*}', '}', raw)
raw = re.sub(r',\s*]', ']', raw)
# Escape single quotes inside strings
raw = re.sub(r"(?<!\\)'", '"', raw)
try:
return json.loads(raw)
except json.JSONDecodeError:
# Last attempt: json5 or demo-parser
import json5
return json5.loads(raw)
Fallback Strategy
If JSON is invalid after three attempts, I switch to a model with stronger support for structured output or to a regular text mode with subsequent parsing. More about fallbacks in the guide.
PROVIDERS = [
{"model": "gpt-4o-mini", "json_mode": True},
{"model": "claude-3-5-haiku", "json_mode": False},
]
def robust_json_request(messages: list, schema: dict):
for provider in PROVIDERS:
try:
if provider["json_mode"]:
return request_with_retry(messages, schema)
else:
response = call_claude(messages)
raw = extract_json(response)
return validate_json(raw, schema)
except Exception as e:
print(f"Provider {provider['model']} did not work: {e}")
continue
raise RuntimeError("All providers returned invalid JSON")
Handling Partially Valid Data
Sometimes the model returns JSON with extra fields or null in required fields. I apply a policy: fill null with default values, drop extra fields, but log discrepancies.
def coerce_data(data: dict, schema: dict) -> dict:
result = {}
for prop, prop_schema in schema["properties"].items():
value = data.get(prop)
if value is None:
if prop_schema["type"] == "string":
value = ""
elif prop_schema["type"] == "number":
value = 0
elif prop_schema["type"] == "boolean":
value = False
elif prop_schema["type"] == "array":
value = []
log_missing_field(prop)
result[prop] = value
return result
Quality Monitoring
I collect metrics: the proportion of successful validations on the first attempt, average number of retries, types of errors. This helps choose the model and prompt. More about observability in the post.
Conclusion
JSON mode saves time but does not exempt from validation. I always pass the schema, check the output, and anticipate retries. If the provider does not support JSON mode, I use extraction and repair. Such a pipeline provides a stable structured output for production.