Sub topic 5
JSON mode: valid JSON, not necessarily your schema
This chapter assumes you can write basic Python with classes and exceptions, read JSON, and have called an LLM API at least once. It also assumes you know what a Pydantic model and a JSON Schema are from the earlier chapters.
Prompting for a format ("reply with JSON only") works most of the time, but it can fail in ways that break a parser. JSON mode is the first provider feature that fixes part of that problem. It fixes less than the name suggests, and the gap between what it promises and what people assume is the source of most bugs with it.
What JSON mode guarantees
JSON mode is a request setting that makes the model's reply a syntactically valid JSON document. The provider enforces this during generation, so you do not rely on the model following your instructions.
With JSON mode on, you can expect:
- No Markdown code fence around the reply.
- No sentence such as "Here is your JSON:" before the object.
- No trailing commas, single-quoted strings, or unescaped newlines inside strings.
json.loadssucceeds on the reply, with one exception covered below (truncation).
JSON mode does not guarantee:
- That the keys are the ones you asked for.
- That required keys are present.
- That values have the right types, or are in your allowed set.
- That the top-level value is an object. Some providers restrict it to an object, others do not.
- That the reply is complete, if the model hit the output token limit.
The distinction is between syntax and shape. JSON mode controls syntax. Your schema describes shape. Everything about shape still needs validation on your side.
How you turn it on
The setting is named differently by each provider, so check your provider's documentation. Two common forms:
| Provider style | Typical setting |
|---|---|
| OpenAI Chat Completions | `response_format={"type": "json_object"}` |
| Google Gemini | `response_mime_type="application/json"` in the generation config |
Some providers pair JSON mode with a stricter feature that accepts a schema. That stricter feature is the topic of the next chapter. When a provider offers both, the schema-accepting option is usually the better choice. JSON mode remains useful when a provider offers only that option, when your schema uses features the strict option rejects, or when the output shape is deliberately loose.
A request with OpenAI-style JSON mode
from openai import OpenAI
client = OpenAI() # reads OPENAI_API_KEY from the environment
ticket_text = "I was charged twice for my March invoice. Please fix this today."
response = client.chat.completions.create(
model="gpt-4o-mini",
response_format={"type": "json_object"},
messages=[
{
"role": "system",
"content": (
"You triage support tickets. Reply with a JSON object with keys "
"category (billing, bug, feature_request, or other), "
"priority (integer 1 to 3, 1 is most urgent), "
"and summary (one sentence)."
),
},
{"role": "user", "content": ticket_text},
],
)
choice = response.choices[0]
print(choice.finish_reason)
print(choice.message.content)Two details in this request matter.
First, the system message says "JSON" and lists the keys. OpenAI's API rejects a JSON-mode request if no message mentions the word JSON. The reason is practical. If you do not tell the model what to produce, it may emit whitespace until it runs out of tokens, because every whitespace-only string is still a valid prefix of a JSON document.
Second, the key names and allowed values live in the prompt, not in the setting. JSON mode never sees them. That is why the prompt must describe the shape, even though a schema exists elsewhere in your code.
The gap between valid JSON and valid data
The following program runs without an API key. It simulates three replies that JSON mode could legitimately return for the same request and checks each at two levels: does it parse, and does it match the schema?
import json
from typing import Literal
from pydantic import BaseModel, Field, ValidationError
class TicketTriage(BaseModel):
category: Literal["billing", "bug", "feature_request", "other"]
priority: int = Field(ge=1, le=3, description="1 is most urgent, 3 is least urgent")
summary: str = Field(max_length=200, description="One-sentence summary of the ticket")
replies = {
"matches the schema": (
'{"category": "billing", "priority": 1, '
'"summary": "Customer was charged twice for March."}'
),
"wrong key names": (
'{"type": "billing", "urgency": "high", '
'"description": "Customer was charged twice."}'
),
"right keys, wrong values": (
'{"category": "payment", "priority": 5, '
'"summary": "Customer was charged twice."}'
),
}
for label, raw in replies.items():
print(f"--- {label}")
try:
json.loads(raw)
print("json.loads: ok")
except json.JSONDecodeError as err:
print("json.loads failed:", err)
continue
try:
ticket = TicketTriage.model_validate_json(raw)
print("schema: ok ->", ticket)
except ValidationError as err:
print(f"schema: {err.error_count()} error(s)")
for item in err.errors():
print(" ", item["loc"], item["type"])All three replies pass json.loads. Only the first passes the schema. The second fails because required fields are missing, and the third fails because the enum and range constraints are violated. This is the typical shape of JSON-mode failures. The parser never complains, so the bug appears later, as a KeyError deep in your code or as a bad value stored in a database.
Why the model still drifts from your schema
The model sees your prompt as text. It predicts tokens that fit the prompt, and JSON mode only removes tokens that would make the document invalid JSON. Several things can go wrong within that remaining space.
- Key drift. The prompt says
category, and the model writestype,Category, orticket_category. This is more likely when the key list is vague or appears only in an example. - Type drift.
"priority": "1"(a string) or"priority": "high"instead of an integer. - Value drift.
"category": "Billing"or"payment"instead of an allowed enum value. - Missing or extra fields. The model omits a field it considers unknown, or adds an
"explanation"field you did not ask for. - Wrong top-level shape. You wanted an object, and you got a list of objects when the ticket mentioned two problems.
- Nesting drift. The model wraps the result, for example
{"result": {...}}or{"ticket": {...}}.
Stronger models drift less, and clear prompts reduce it, but none of this is ruled out. Plan for it by validating every reply.
A safe pattern for JSON mode
Use JSON mode as one layer in a pipeline, not as the whole pipeline. The function below checks the finish reason, parses, and validates. It uses the TicketTriage model from the previous example and accepts the response object from the earlier request.
import json
from pydantic import ValidationError
class StructuredOutputError(Exception):
"""Raised when a reply cannot be turned into a valid TicketTriage."""
def parse_ticket(response) -> TicketTriage:
choice = response.choices[0]
if choice.finish_reason == "length":
raise StructuredOutputError("Reply was cut off by the token limit")
if choice.finish_reason == "content_filter":
raise StructuredOutputError("Reply was blocked by a content filter")
content = choice.message.content
if not content:
raise StructuredOutputError("Reply was empty")
try:
return TicketTriage.model_validate_json(content)
except ValidationError as err:
raise StructuredOutputError(f"Schema mismatch: {err}") from errmodel_validate_json parses and validates in one step. A syntax error also raises ValidationError, so one except clause covers both. The finish_reason check comes first because a truncated reply is the one case where JSON mode can still produce invalid JSON. If the model stops mid-object, no later token closes the brace. Retrying a truncated reply with the same limit usually truncates again, so treat it as its own error and consider raising max_tokens or shortening the task.
Other providers use different names for the finish reason (stop_reason, finishReason, and so on). The check is the same: confirm the model finished normally before trusting the content.
Prompting well in JSON mode
Because the setting does not carry your schema, the prompt has to. These habits reduce drift:
- List every key with its type and allowed values. Write "priority: integer from 1 to 3" rather than "priority".
- Include the generated JSON Schema. For a Pydantic model,
json.dumps(TicketTriage.model_json_schema())gives the prompt a single source of truth, so the prompt and the validator cannot disagree. - Show one example reply. Examples teach key names and formatting faster than descriptions do. Keep the example realistic and different from the live input, or the model may copy its values.
- State what to do when information is missing. For example: "Use null for unknown fields." Without this, a model that cannot fill a field may invent a value.
- Say the top-level type. "Reply with a single JSON object" prevents wrapper arrays.
Building the prompt from the model keeps the pieces consistent:
import json
schema_text = json.dumps(TicketTriage.model_json_schema(), indent=2)
system_prompt = (
"You triage support tickets. Reply with a single JSON object that conforms "
"to this JSON Schema, with no other keys:\n\n" + schema_text
)
print(system_prompt)Pydantic's schema output includes the descriptions you attached with Field, so those hints reach the model for free.
When JSON mode is the right choice
| Situation | JSON mode fits? |
|---|---|
| The provider offers no schema-constrained option | Yes, with validation and retries |
| The output shape varies, such as open-ended key-value extraction | Yes, validate only what you need |
| Your schema uses features the strict option rejects | Possibly, with careful validation |
| The shape is fixed and the provider supports schema enforcement | Prefer the schema-constrained option |
| You need guarantees about enum values or required keys | No, JSON mode cannot give them |
Common mistakes
- Treating a successful
json.loadsas success. It only proves the syntax is valid. - Using
dict.getwith defaults to hide missing keys. This turns a schema failure into silently wrong data. Validate first, then access fields. - Forgetting the word "JSON" in the prompt on providers that require it, or omitting the key list because "the setting handles it".
- Skipping the finish-reason check. A cut-off reply looks like a parse error and gets misdiagnosed as a prompt problem.
- Assuming the top level is always an object. Check, or let the Pydantic model do it.
The next chapter covers schema-constrained decoding, which moves the shape guarantees from your validator into the generation step itself. Validation stays in your pipeline either way, because constrained output can still be wrong in meaning.
Exercise
A JSON-mode request for the TicketTriage schema returns {"category": "Billing", "priority": 2, "summary": "Double charge."}. json.loads succeeds. Does TicketTriage.modelvalidatejson accept it, and what does that tell you about JSON mode?
Show answer
It rejects the reply. The Literal type allows only lowercase "billing", and "Billing" is not in the set, so Pydantic raises a ValidationError on the category field. JSON mode guaranteed only that the text was valid JSON. It did not know the allowed values, so the shape check must happen in your own code.
Exercise
A reply arrives with finishreason "length" and the content {"category": "bug", "priority": 1, "summary": "The export button. Why should you handle this case before calling modelvalidate_json, and what is a sensible response?
Show answer
The reply was cut off at the token limit, so the JSON is incomplete and cannot parse. Checking the finish reason first lets you report the real cause. Retrying with the same limit will likely cut off again, so raise the output token limit or shorten the task, then retry.