The short answer
#Do not ask for JSON in the prompt and hope. Give the API a JSON schema through output_config.format and the response is constrained to match it: valid JSON, the right keys, the right types, no code fences, no "Here is the JSON:". With Zod you get the same thing plus a typed result in one call.
_20import Anthropic from '@anthropic-ai/sdk';_20import { zodOutputFormat } from '@anthropic-ai/sdk/helpers/zod';_20import { z } from 'zod';_20_20const Product = z.object({_20 name: z.string(),_20 price: z.number(),_20 category: z.enum(['book', 'clothing', 'electronics', 'other']),_20});_20_20const client = new Anthropic();_20_20const response = await client.messages.parse({_20 model: 'claude-sonnet-5-5',_20 max_tokens: 512,_20 messages: [{ role: 'user', content: `Extract the product from this listing:\n\n${listing}` }],_20 output_config: { format: zodOutputFormat(Product) },_20});_20_20const product = response.parsed_output; // typed as z.infer<typeof Product>
Why asking nicely fails
#A model produces text token by token, and "respond only with JSON" is a request, not a constraint. Most of the time the model complies. Some of the time it wraps the object in markdown fences because it has seen a great deal of code formatted that way, or adds a sentence of explanation, or uses a trailing comma, or invents a key you did not ask for, or returns "price": "£12.99" as a string when you wanted a number. Each of these is rare on its own. Across a few thousand requests a day, rare becomes several times an hour, and every one is a JSON.parse exception or a type error somewhere downstream.
Structured outputs move the guarantee from the prompt to the API. When you supply a schema, the response is generated so that it conforms to that schema. You still write a good prompt, because the schema controls shape, not meaning: it cannot stop the model putting the wrong product in name. But the parsing and type problems go away.
How to do it
#Pass a JSON schema directly
If you do not use Zod, or the schema comes from somewhere else (an OpenAPI document, a database), give it to output_config.format as plain JSON Schema. The response text is a JSON string that matches it.
_23const response = await client.messages.create({_23 model: 'claude-sonnet-5-5',_23 max_tokens: 512,_23 messages: [{ role: 'user', content: `Classify this support ticket:\n\n${ticket}` }],_23 output_config: {_23 format: {_23 type: 'json_schema',_23 schema: {_23 type: 'object',_23 properties: {_23 category: { type: 'string', enum: ['billing', 'bug', 'feature_request', 'other'] },_23 urgent: { type: 'boolean' },_23 summary: { type: 'string' },_23 },_23 required: ['category', 'urgent', 'summary'],_23 additionalProperties: false,_23 },_23 },_23 },_23});_23_23const block = response.content.find((b) => b.type === 'text');_23const result = block?.type === 'text' ? JSON.parse(block.text) : null;
Set additionalProperties: false and list every key in required. That rules out surprise fields and optional-but-missing fields, which are the two things that most often break the code that consumes the result.
Use Zod and let the SDK parse
zodOutputFormat() converts a Zod schema to the JSON Schema the API expects, and client.messages.parse() parses the text and validates it against the same Zod schema before handing it back as parsed_output. You write the schema once and get a runtime check and a TypeScript type from it.
Keep the schema and the prompt next to each other. The field names and .describe() text are visible to the model and act as part of the instructions, so z.string().describe('Full name as written on the invoice') is more useful than z.string().
Validate anyway
Treat parsed_output as untrusted input that happens to be well shaped. If the model stopped early or the API returned something unexpected, it may be missing. And a value can satisfy the schema while being wrong for your application: a price of -4, a date in the year 20026, an email address with no @.
_10if (!response.parsed_output) {_10 throw new Error(`No structured output, stop_reason=${response.stop_reason}`);_10}_10if (response.parsed_output.price <= 0) {_10 throw new Error('Price must be positive');_10}
Put business rules in the Zod schema where you can (z.number().positive(), z.string().email()). The API enforces the JSON Schema it was given; the Zod refinements run client-side in parse() and give you a clear failure instead of bad data.
Handle truncation
max_tokens is a hard stop. If the model hits it halfway through an object, you get half an object, which is not valid JSON no matter what schema you supplied. Check stop_reason.
_10if (response.stop_reason === 'max_tokens') {_10 // The output was cut off. Raise max_tokens or ask for less._10}
Set max_tokens with headroom for the largest realistic result. For a list of items, cap the list in the prompt and the schema (z.array(Item).max(20)) so the size is bounded on both ends.
Keep schemas small and flat
A schema with four levels of nesting, optional unions and twenty fields gives the model more ways to be subtly wrong and makes failures harder to debug. Prefer a flat object with a handful of fields. If you need a lot of information, make two or three focused calls rather than one enormous one; each is cheaper to retry and easier to test.
Use enums for categories
Any field that is really a choice from a fixed set should be an enum, not a free string. z.enum(['low', 'medium', 'high']) means you never have to handle "Medium", "med" and "moderate" in a switch statement. Include an 'other' or 'unknown' option so the model has somewhere to put the cases that genuinely do not fit, rather than forcing a bad match.
Common pitfalls
#- Asking for JSON in the prompt and not using a schema. It works in testing and fails in production. The schema costs one extra object in the request.
- Optional fields everywhere.
z.string().optional()on every field means every consumer has to handleundefined. Mark a field optional only when its absence has a meaning. - Ignoring
stop_reason****. A truncated response is the most common reason for a "valid schema, invalid JSON" report. Check it before you blame the model. - Nullable versus optional. If the model should say "no value", give it an explicit
null(z.number().nullable()) rather than leaving the key out. It is easier to generate and easier to check. - Mixing prose and JSON in one response. If you also want an explanation, give it its own field in the schema (
reasoning: z.string()) rather than asking for a paragraph followed by an object. - Expecting the schema to fix the prompt. Structured outputs guarantee shape. If the extracted values are wrong, improve the instructions and examples in the prompt.
Related reading
#quick question
Was this resource helpful?
by Danny