Getting JSON from an AI used to feel like herding cats. Now with GPT-5, function calling, and strict response formats, it’s finally predictable. Let’s talk about why GPT-4 made it painful, why GPT-5 nailed it, and how Claude Sonnet 4.5 and Gemini 2.5 handle structure today.
A year ago, asking an AI for clean JSON was like asking Sam Bankman-Fried for accounting advice — you’d get a confident answer, but you’d still end up in court.
That’s changed.
Why GPT-4 Made It Painful
GPT-4 could imitate JSON, but it didn’t respect it.
You’d say “respond only in JSON,” and it would — until it decided to be polite and wrap your object in a paragraph.
It was trained to sound helpful, not to be parsable. So you got answers that looked structured but broke the moment you called JSON.parse().
Even with few-shot prompting and hard system rules like
“Output valid JSON only. No markdown. No text.”
you still had to babysit it. It was like relying on a chatty intern to handle your database exports — enthusiastic, but dangerous.
Why GPT-5 Finally Gets It
GPT-5 turned “structured mode” into a native behavior.
Between function calling, response_format: "json", and schema enforcement, the model now thinks in structure.
Instead of hoping it replies in JSON, you give it a function schema — and it populates the arguments directly.
No prose. No markdown fences. No rogue explanations.
{
"feedback": {
"clarity_score": 8,
"readability": "good",
"recommendations": ["tighten intro", "clarify metrics"]
}
}
And yes, that passes a validator the first time.
GPT-5 doesn’t just mimic JSON patterns; it treats them like part of the reasoning path. It’s the first time “structured output” actually means structured.
Claude Sonnet 4.5: The Philosopher-Engineer
Claude Sonnet 4.5 is eerily good at reasoning, and Anthropic’s new Structured Output API closed most of the gaps Sonnet 3.5 had.
Define your schema, and it’ll respect it — almost religiously — though it still occasionally adds a whisper of natural language if the schema leaves wiggle room.
Claude’s strength is contextual depth: it can give nuanced, multidimensional feedback inside a strict schema — like explaining why a section failed clarity while still producing perfectly valid JSON.
Use Sonnet 4.5 when you want thoughtful structure — feedback with soul that still parses.
Gemini 2.5 Pro: The Architect with Opinions
Gemini 2.5 finally got serious about structure. Google’s Response Mode = JSON actually works now — mostly.
It’s fast, and the JSON it returns is clean as long as you don’t tempt it with ambiguity.
But Gemini still has that Google-brain tendency to “improve” things. If your schema has redundant fields, it may silently optimize them out.
On the plus side, it’s great for speed and short responses. On the downside, it’s a bit like a TypeScript compiler that thinks it knows better than you.
Pro tip: keep your schema tight, limit optional fields, and validate aggressively.
Why This Matters
Structured feedback is the bridge between language and action.
Once you can get machine-readable reasoning, you can automate judgment — code review, content scoring, user feedback loops, anything.
GPT-5 made that consistent.
Claude Sonnet 4.5 made it thoughtful.
Gemini 2.5 made it fast.
Pick your flavor — but the days of regex-cleaning hallucinated brackets are finally behind us.
The Practical Stack
If you’re building systems on top of structured AI feedback:
- Use GPT-5’s response_format: "json" or function calls. They’re bulletproof.
- Validate everything. Pydantic, Zod, JSON Schema — pick your poison.
- Keep temperature at 0.0. Creativity breaks structure.
- Separate reasoning from output. If you need both, use two steps — explanation first, structure second.
Final Thought
Getting JSON from AI used to be a party trick.
Now it’s infrastructure.
GPT-5 made the structure real.
Claude Sonnet 4.5 brought the reasoning.
Gemini 2.5 added speed.
Code Appendix: Enforcing JSON Across GPT-5, Claude 4.5, and Gemini 2.5
We’ll use one shared schema and show three provider-specific ways to make the model stay inside the brackets.
0) Shared schema (Zod) + runtime validator
import { z } from "zod";
export const FeedbackSchema = z.object({
feedback: z.object({
clarity_score: z.number().int().min(0).max(10),
readability: z.enum(["poor", "okay", "good", "great"]),
recommendations: z.array(z.string()).max(10)
})
});
export type Feedback = z.infer<typeof FeedbackSchema>;
// tiny helper
export function parseOrThrow(jsonText: string): Feedback {
const parsed = JSON.parse(jsonText);
return FeedbackSchema.parse(parsed);
}
1) OpenAI GPT-5 — function calling or JSON response format
A) Function calling (argument object, zero prose)
import OpenAI from "openai";
const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY! });
const functionDef = {
name: "submit_feedback",
description: "Return structured feedback JSON",
parameters: {
type: "object",
properties: {
feedback: {
type: "object",
properties: {
clarity_score: { type: "integer", minimum: 0, maximum: 10 },
readability: { type: "string", enum: ["poor","okay","good","great"] },
recommendations: { type: "array", items: { type: "string" }, maxItems: 10 }
},
required: ["clarity_score","readability","recommendations"],
additionalProperties: false
}
},
required: ["feedback"],
additionalProperties: false
}
} as const;
const res = await openai.chat.completions.create({
model: "gpt-5", // ← use your exact model name
messages: [
{ role: "system", content: "Return ONLY via the provided function." },
{ role: "user", content: "Score this intro and give improvement tips." }
],
tools: [{ type: "function", function: functionDef }],
tool_choice: { type: "function", function: { name: "submit_feedback" } },
temperature: 0
});
// extract function arguments safely
const toolCall = res.choices[0]?.message?.tool_calls?.[0];
const argsJson = toolCall?.function?.arguments ?? "{}";
const data = FeedbackSchema.parse(JSON.parse(argsJson));
B) Enforced JSON (response_format)
const res = await openai.chat.completions.create({
model: "gpt-5",
messages: [
{ role: "system", content: "Respond with strictly valid JSON only." },
{ role: "user", content: "Score this intro and suggest improvements." }
],
response_format: {
type: "json_schema",
json_schema: {
name: "Feedback",
schema: {
type: "object",
properties: {
feedback: {
type: "object",
properties: {
clarity_score: { type: "integer", minimum: 0, maximum: 10 },
readability: { type: "string", enum: ["poor","okay","good","great"] },
recommendations: { type: "array", items: { type: "string" }, maxItems: 10 }
},
required: ["clarity_score","readability","recommendations"],
additionalProperties: false
}
},
required: ["feedback"],
additionalProperties: false
},
strict: true
}
},
temperature: 0
});
const jsonText = res.choices[0].message.content!;
const data = parseOrThrow(jsonText);
When to use which:
- Use function calling when you’re chaining tools or want arguments separate from text.
- Use response_format when you want a pure JSON string you can log/pipe directly.
2) Anthropic Claude Sonnet 4.5 — Structured Output API
import Anthropic from "@anthropic-ai/sdk";
const anthropic = new Anthropic({ apiKey: process.env.ANTHROPIC_API_KEY! });
const res = await anthropic.messages.create({
model: "claude-4.5-sonnet",
system: "Return strictly valid JSON that matches the provided schema.",
messages: [{ role: "user", content: "Score this intro and propose fixes." }],
temperature: 0,
response_format: {
type: "json_schema",
json_schema: {
name: "Feedback",
schema: {
type: "object",
properties: {
feedback: {
type: "object",
properties: {
clarity_score: { type: "integer", minimum: 0, maximum: 10 },
readability: { type: "string", enum: ["poor","okay","good","great"] },
recommendations: { type: "array", items: { type: "string" }, maxItems: 10 }
},
required: ["clarity_score","readability","recommendations"],
additionalProperties: false
}
},
required: ["feedback"],
additionalProperties: false
},
strict: true
}
}
});
// Claude returns content blocks; pick the text block
const jsonText = res.content.map(b => ("text" in b ? b.text : "")).join("");
const data = parseOrThrow(jsonText);
Notes: Claude can still “explain” if your schema leaves holes. Keep strict: true, and don’t include optional text fields unless you’ll accept them.
3) Google Gemini 2.5 Pro — JSON mode + response schema
import { GoogleGenerativeAI } from "@google/generative-ai";
const genAI = new GoogleGenerativeAI(process.env.GOOGLE_API_KEY!);
const model = genAI.getGenerativeModel({
model: "gemini-2.5-pro",
generationConfig: {
temperature: 0,
responseMimeType: "application/json",
responseSchema: {
type: "OBJECT",
properties: {
feedback: {
type: "OBJECT",
properties: {
clarity_score: { type: "INTEGER" },
readability: { type: "STRING", enum: ["poor","okay","good","great"] },
recommendations: { type: "ARRAY", items: { type: "STRING" } }
},
required: ["clarity_score","readability","recommendations"]
}
},
required: ["feedback"]
}
}
});
const res = await model.generateContent({
contents: [{ role: "user", parts: [{ text: "Score this intro and give fixes." }]}]
});
const jsonText = res.response.text(); // JSON string because of responseMimeType
const data = parseOrThrow(jsonText);
Notes: Gemini is fast and clean in JSON mode, but it may “optimize” your schema if it’s ambiguous. Keep fields required where possible and validate every response.
4) Retry strategy (universal, dead simple)
async function withJsonRetry<T>(
fn: () => Promise<string>,
validate: (s: string) => T,
tries = 2
): Promise<T> {
let lastErr: unknown;
for (let i = 0; i < tries; i++) {
try {
const out = await fn();
return validate(out);
} catch (err) {
lastErr = err;
}
}
throw lastErr;
}
Use this wrapper around any of the above to auto-retry on schema/parse hiccups.
5) Prompt hygiene checklist (copy/paste)
- System: “Respond with strictly valid JSON that conforms to the provided schema. No markdown, no prose.”
- Temperature: 0.0
- One schema, no synonyms, no optional fields unless you accept null.
- Keep examples out unless they’re strictly JSON and match your schema 1:1.
- Always validate (Zod/Pydantic/JSON Schema). Never trust raw strings.
