# Reliable Structured JSON Output Pattern

> Get valid, schema-conforming JSON from any model using native structured outputs where available, and validate-and-repair otherwise.

Category: Prompt & Agent Patterns  
Tags: json, schema, validation, extraction  
Setup time (estimate): 30 minutes  
Estimated cost: Repairs add an extra call only on failures.  
Last verified: not yet independently verified

## Order of preference

1. **Native structured outputs** (e.g. OpenAI `response_format: {type: "json_schema", ...}` with `strict: true`, or tool calling with a schema).
2. **JSON mode** plus schema in the prompt.
3. **Prompt-only** plus validation and a repair retry.

## Prompt (fallback path)

```text
Extract the fields below from the text. Return ONLY a JSON object matching this schema,
with no markdown fences or commentary. Use null for unknown values; do not guess.
Schema: {"name": string, "email": string|null, "company": string|null}
Text: """{{input}}"""
```

## Validate and repair

```python
import json, jsonschema

def get_json(call, prompt, schema, retries=2):
    msg = prompt
    for _ in range(retries + 1):
        raw = call(msg)
        try:
            data = json.loads(raw)
            jsonschema.validate(data, schema)
            return data
        except Exception as e:
            msg = f"{prompt}\n\nYour previous output was invalid: {e}. Return corrected JSON only."
    raise ValueError("Could not obtain valid JSON")
```

## Failure modes

- Schema-valid output can still be semantically wrong; add business-rule checks.
- Repair loops without a limit; cap retries.
- Providers support different schema features; test each.
