Fix OpenAI JSON Mode Errors
OpenAI's JSON mode and structured outputs reduce invalid JSON — but don't eliminate it. Truncation, token limits, and format drift still cause parse failures. Here's how to handle every case.
Repair JSON Now →Paste your broken OpenAI JSON output →
Open JSON Repair Tool →Free · No signup · Browser-side processing
5 Most Common OpenAI JSON Errors
Truncated JSON (most common)
max_tokens reached before JSON was complete
Broken
{"name": "Alice", "items": [{"id": 1, "title": "Foo",Fixed
{"name": "Alice", "items": [{"id": 1, "title": "Foo"}]}Auto-fix: AI JSONMedic closes unclosed strings, arrays, and objects intelligently
Markdown code fences
Model wraps JSON in ```json even with JSON mode enabled
Broken
```json
{"result": "success"}
```Fixed
{"result": "success"}Auto-fix: Strips markdown fences and prose prefixes automatically
Trailing commas
Model generates JavaScript-style commas after last property
Broken
{"name": "Alice", "active": true,}Fixed
{"name": "Alice", "active": true}Auto-fix: Removes trailing commas in objects and arrays
Undefined / missing values
Model emits undefined or NaN for missing numeric fields
Broken
{"score": NaN, "rank": undefined}Fixed
{"score": null, "rank": null}Auto-fix: Converts NaN, Infinity, and undefined to null
Unquoted keys
Model uses JavaScript object literal syntax
Broken
{name: "Alice", active: true}Fixed
{"name": "Alice", "active": true}Auto-fix: Adds double quotes around all unquoted object keys
Production-Safe Code Patterns
Pattern 1: Parse → Repair Fallback (Recommended)
// Safe pattern: try parse, repair if fails
import { repairJson } from 'ai-json-medic'; // or use the API
async function parseOpenAIResponse(content: string) {
// First try: direct parse
try {
return JSON.parse(content);
} catch {
// Second try: repair via API
const res = await fetch('https://aijsonmedic.com/api/repair', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ input: content }),
});
const { output, valid } = await res.json();
if (valid) return JSON.parse(output);
throw new Error('Could not repair JSON: ' + content.slice(0, 100));
}
}
// Usage with OpenAI SDK
const completion = await openai.chat.completions.create({
model: 'gpt-4o',
messages: [{ role: 'user', content: 'Return a JSON object...' }],
response_format: { type: 'json_object' },
max_tokens: 2000, // set high enough to avoid truncation
});
const data = await parseOpenAIResponse(completion.choices[0].message.content);Pattern 2: Structured Outputs (Most Reliable)
// Best pattern: structured outputs with JSON Schema
const completion = await openai.chat.completions.create({
model: 'gpt-4o-2024-08-06', // structured outputs require this model+
messages: [{ role: 'user', content: 'Extract the user profile...' }],
response_format: {
type: 'json_schema',
json_schema: {
name: 'user_profile',
strict: true,
schema: {
type: 'object',
properties: {
name: { type: 'string' },
age: { type: 'integer' },
tags: { type: 'array', items: { type: 'string' } },
},
required: ['name', 'age', 'tags'],
additionalProperties: false,
},
},
},
});
// structured outputs: parse is safer, but still wrap in try/catch
try {
const data = JSON.parse(completion.choices[0].message.content);
} catch {
// Use AI JSONMedic as fallback for edge cases
}JSON Mode vs Structured Outputs
| Feature | JSON Mode | Structured Outputs |
|---|---|---|
| Valid JSON guaranteed | ~95% | ~99% |
| Schema enforcement | ✗ No | ✓ Yes (JSON Schema) |
| Truncation risk | Yes | Yes (same limit) |
| Requires schema definition | No | Yes |
| Model support | All GPT models | gpt-4o-2024-08-06+ |
| Still needs try/catch? | Yes | Recommended |
| Cost | Same | Same |
FAQ
Why does OpenAI JSON mode still produce invalid JSON?
OpenAI JSON mode reduces but does not eliminate invalid JSON. Common causes: token limit truncation (incomplete response), model generating markdown alongside JSON, schema mismatches, and context window pressure causing format drift.
What is the difference between JSON mode and structured outputs?
JSON mode (response_format: {type: "json_object"}) requests valid JSON but does not guarantee a specific schema. Structured outputs (response_format: {type: "json_schema"}) enforces a JSON Schema and is more reliable, but still subject to truncation at max_tokens.
How do I prevent JSON parse errors with OpenAI?
Best practices: set a generous max_tokens, use structured outputs with a JSON Schema, wrap JSON.parse() in try/catch, use the AI JSONMedic API as a fallback repair step, and prompt the model to output JSON only with no surrounding text.
Related Tools & Guides
Repair OpenAI JSON in Seconds
Paste any broken JSON output. The repair engine handles all the patterns above automatically.
Open JSON Repair Tool →