Lesson 2 of 7
Structured outputs (JSON)
7 min read
Your prototype works in the demo. Then the model answers 'Sure! The total is around fifty-nine dollars 🙂' and your parser — expecting a number — falls over. How do you make the reply a shape, not a vibe?
Prose is for people; code needs a shape
Ask for an order total and a chatty model gives you a sentence. Lovely to read, miserable to parse — the wording drifts every call, so parseFloat is a coin flip. The fix is to stop asking for text and start demanding a structure: name the fields you want and the types they must be.
Free text reads well but its shape changes every time. A schema pins the reply to fixed fields and types your code can rely on.
Ask for JSON, or enforce it
There are two strengths of this. The weak version: ask for JSON in the prompt and hope — it usually works, but a stray sentence or a missing field will bite you in production. The strong version: use the provider's structured output or tool schema so the shape is enforced — every field present, every type correct, no prose to strip. Reach for the enforced version whenever the output feeds code.
Asking for JSON is a suggestion; a schema is a guarantee. When the reply feeds another system, guarantee the shape.
Even with valid JSON, the values can be wrong — a schema enforces structure, not truth. Validate ranges and enums, and never trust a number just because it parsed.
The shape of it
- —Free text is for humans; structured JSON is for code.
- —Asking for JSON in the prompt is best-effort — it can still drift or omit a field.
- —A schema (structured output / tool call) enforces fields and types.
- —A schema guarantees shape, not correctness — still validate the values.
You need the model's answer to drop straight into a database row, no cleanup. What's the most reliable approach?
Continue in the app
Take the whole Building AI Apps with the API course — tracked
Get your personalized path, progress and streaks in the app — this lesson and every next one, in order.