JSON Mode: Hidden Issues and How to Work Around Them
JSON mode is a convenient way to make a model return structured data. In practice, it solves some problems but creates new ones. Below are the typical pitfalls that arise when integrating JSON mode in production, and how to work around them.
What is JSON mode and why is it needed
JSON mode is a generation mode where the model guarantees to return valid JSON. Providers implement it differently: some use grammatical constraints at the decoding level, others use post-processing. In any case, the developer does not need to parse the response with regular expressions and hope that the model did not forget to close a bracket.
JSON mode is used for tasks where machine-readable output is required: entity extraction, classification, metadata generation. Without it, the model may return text with explanations, markdown formatting, or simply cut off the response mid-word.
Hidden issues of JSON mode
1. Invalid JSON is still possible
JSON mode does not eliminate model limitations. If the context is full or the request is too complex, the model may return an empty object, null, or a truncated JSON. This is especially noticeable with long responses—the model hits the token limit and cuts off the output in the middle of the structure.
2. Field loss and schema mismatch
The model may skip optional fields or return a value of a different type than expected by the schema. For example, a string instead of a number, or an object instead of an array. JSON mode guarantees syntax but not semantics.
3. Conflict with streaming
JSON mode works inconsistently with streaming generation. Some providers do not support using streaming and JSON mode simultaneously, while others return partial JSON fragments that cannot be parsed until the stream is complete.
4. Impact of temperature and top_p
High temperature increases the likelihood of syntax errors even in JSON mode. With temperature > 1, the model may start to 'fantasize' and break the structure. For JSON mode, it is recommended to keep the temperature in the range of 0–0.3.
5. Differences in provider implementation
Each provider has its own request format. In some places, you need to pass response_format: {type: 'json_object'}, in others json_mode: true, and in others simply add the word 'JSON' to the prompt. This complicates the creation of a universal client.
Practical processing pipeline
Below is a pipeline that survives most JSON mode issues. It consists of three stages.
Stage 1: Request with JSON mode and low temperature
response = client.chat.completions.create(
model='model-name',
messages=[
{'role': 'system', 'content': 'You are an assistant who returns only JSON.'},
{'role': 'user', 'content': prompt}
],
response_format={'type': 'json_object'},
temperature=0.1,
max_tokens=1024
)
Stage 2: Parsing and validation
import json
from jsonschema import validate, ValidationError
raw = response.choices[0].message.content
try:
data = json.loads(raw)
validate(instance=data, schema=MY_SCHEMA)
except (json.JSONDecodeError, ValidationError) as e:
# Log the error and proceed to fallback
handle_parse_error(raw, e)
Stage 3: Fallback without JSON mode
If JSON mode fails, a repeat request is sent without it, but with a stricter prompt and a request to return JSON in a markdown block. The JSON is then extracted from the block using a regular expression.
import re
def extract_json_from_markdown(text: str) -> dict:
match = re.search(r'```json\n(.*?)\n```', text, re.DOTALL)
if not match:
raise ValueError('JSON not found in markdown block')
return json.loads(match.group(1))
This fallback works in 95% of cases when the main JSON mode fails.
Comparison of approaches to structured output
| Approach | Syntax guarantee | Schema guarantee | Cost | Complexity |
|---|---|---|---|---|
| JSON mode | High | No | Low | Low |
| JSON mode + validation | High | Partial | Low | Medium |
| Function calling | High | High | Medium | Medium |
| Grammatical constraints | Full | Full | High | High |
JSON mode is used for simple schemas; function calling is used when strict type validation is needed. For critical scenarios—grammatical constraints, but this requires custom inference.
Recommendations
- Always validate the JSON response, even if you use JSON mode. The schema is your main protector against 'fantasies' of the model.
- Keep the temperature low. Creativity is not needed for structured output.
- Do not use streaming with JSON mode if it is not explicitly supported by the provider.
- Design the schema with possible field omissions in mind. Make fields optional if it is acceptable.
- Always have a fallback strategy. JSON mode is not a silver bullet.
For more on validating structured output, read the guide on structured-output-validation. For more on JSON schema, see the glossary of JSON Schema. If you are just starting with LLM API, check out the introduction to LLM for beginners.