---
title: "How do I get reliable JSON out of an LLM?"
description: "Use structured outputs: pass a JSON schema in output_config.format, or a Zod schema through zodOutputFormat and messages.parse, then validate and handle truncation."
url: https://www.danny.engineering/answer/ai/how-do-i-get-reliable-json-out-of-an-llm
author: Danny
published: 2026-12-03T00:00:00.000Z
updated: 2026-12-03T15:34:00.000Z
tags: ["AI"]
---

# How do I get reliable JSON out of an LLM?

## 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.


```typescript
import Anthropic from '@anthropic-ai/sdk';
import { zodOutputFormat } from '@anthropic-ai/sdk/helpers/zod';
import { z } from 'zod';

const Product = z.object({
  name: z.string(),
  price: z.number(),
  category: z.enum(['book', 'clothing', 'electronics', 'other']),
});

const client = new Anthropic();

const response = await client.messages.parse({
  model: 'claude-sonnet-5-5',
  max_tokens: 512,
  messages: [{ role: 'user', content: `Extract the product from this listing:\n\n${listing}` }],
  output_config: { format: zodOutputFormat(Product) },
});

const 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.


```typescript
const response = await client.messages.create({
  model: 'claude-sonnet-5-5',
  max_tokens: 512,
  messages: [{ role: 'user', content: `Classify this support ticket:\n\n${ticket}` }],
  output_config: {
    format: {
      type: 'json_schema',
      schema: {
        type: 'object',
        properties: {
          category: { type: 'string', enum: ['billing', 'bug', 'feature_request', 'other'] },
          urgent: { type: 'boolean' },
          summary: { type: 'string' },
        },
        required: ['category', 'urgent', 'summary'],
        additionalProperties: false,
      },
    },
  },
});

const block = response.content.find((b) => b.type === 'text');
const 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 `@`.


```typescript
if (!response.parsed_output) {
  throw new Error(`No structured output, stop_reason=${response.stop_reason}`);
}
if (response.parsed_output.price <= 0) {
  throw new Error('Price must be positive');
}
```


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`.


```typescript
if (response.stop_reason === 'max_tokens') {
  // The output was cut off. Raise max_tokens or ask for less.
}
```


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 handle `undefined`. 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

- [Structured outputs in the Claude docs](https://platform.claude.com/docs/en/build-with-claude/structured-outputs)
- [Understanding JSON Schema](https://json-schema.org/understanding-json-schema)
- [Zod documentation](https://zod.dev/)
- [JSON.parse() on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse)
