# Structured Output

> The Structured Output is a technique of making a language model return data in a strict format such as JSON matching a schema.

## How do I get an LLM to return valid JSON?

The technique of constraining the response of a model to a defined format, usually JSON that matches a JSON Schema. Allows programs to reliably parse model output instead of extracting data from free text.

- Topic: Prompting
- Type: technique

## Example

Wrong:

```js
const res = await llm.generate({ prompt: 'Return the user as JSON.' });
const user = JSON.parse(res.text);
```

Right:

```js
const res = await llm.generate({
  prompt: 'Extract the user from the text.',
  responseFormat: { type: 'json_schema', schema: userJsonSchema },
});
const user = validateUser(JSON.parse(res.text));
```

A schema-constrained response plus validation in code catches missing fields before the data is used.

## Common mistakes

- Output gets cut off by the token limit and the JSON is invalid.
- Wrapping JSON in a markdown code block that breaks `JSON.parse`.

## Key points

- The response is parsed and validated against the schema before use.
- The API's structured output or JSON mode is used, not only a request in the prompt.
- Refusals, truncated output and invalid JSON are handled with a retry or an error.

## Interview questions

### JSON mode vs structured output: what is the difference?

JSON mode only aims for valid JSON. Structured output also constrains the response to a given schema, so required fields and types match.

### Do I still need validation with structured output?

Yes. Output can still be truncated, refused or wrong in meaning, so validate it before use.

### Why does my JSON come wrapped in a code block?

The model formats it like a chat answer. Use the API's structured output, or strip the fence before parsing.

## Related cards

- [JSON Schema](https://wonderium.dev/ai/json-schema.md)
- [Tool Calling](https://wonderium.dev/ai/tool-calling.md)
- [Max Tokens](https://wonderium.dev/ai/max-tokens.md)
- [.json](https://wonderium.dev/engineering/json.md)

---

- Level: [Artificial Intelligence](https://wonderium.dev/ai.md)
- HTML version: https://wonderium.dev/ai/structured-output
- Last updated: 2026-11-25
