Claude Structured Output JSON: Schemas, tool_choice, Retries
Get consistent JSON from Claude: schema design with nullable fields, tool use with tool_choice, few-shot examples and validation with error-fed retries.
Asking Claude to "return JSON" works most of the time, and the failures are what break your pipeline: a trailing comment, a missing field, an invented invoice date. This post shows how to get Claude structured output JSON you can rely on, using the patterns Domain 4 of the CCAR-F exam tests: schema first, tool use, few-shot examples, nullable fields and validation with retry.
Start with the schema, not the prompt
Decide what downstream code needs before writing instructions. For each field, ask: is it always present in the source, is it a closed set of values, and what should happen when the source is ambiguous?
Those answers become schema decisions (Task Statement 4.3):
- Required vs optional. Mark a field required only if every source document contains it. If an invoice may lack a PO number, a required
po_numberpushes the model to make one up. - Nullable fields. Allow
nullfor information that may be missing. A plausible fake value is worse than a null because nothing downstream flags it. - Enums with an escape hatch. For categories, add
"other"plus a free-text detail field, and"unclear"for genuinely ambiguous cases. Otherwise edge cases land in the closest wrong bucket.
Here is an extraction schema that applies all three:
{
"name": "extract_invoice",
"description": "Extract billing data from one supplier invoice.",
"input_schema": {
"type": "object",
"properties": {
"invoice_number": { "type": "string" },
"invoice_date": {
"type": ["string", "null"],
"description": "ISO 8601 date (YYYY-MM-DD). null if no date appears on the invoice."
},
"po_number": { "type": ["string", "null"] },
"category": {
"type": "string",
"enum": ["hardware", "software", "services", "other", "unclear"]
},
"category_detail": {
"type": ["string", "null"],
"description": "Required when category is 'other'."
},
"line_items": {
"type": "array",
"items": {
"type": "object",
"properties": {
"description": { "type": "string" },
"amount": { "type": "number" }
},
"required": ["description", "amount"]
}
},
"stated_total": { "type": "number" },
"calculated_total": { "type": "number" }
},
"required": ["invoice_number", "invoice_date", "po_number", "category", "line_items", "stated_total", "calculated_total"]
}
}
Note the pattern: invoice_date is listed as required but its type allows null. The model must address the field every time, and it has an honest answer available when the date isn't there. The description also carries a normalization rule for inconsistent date formats.
Use tool use and tool_choice to force structure
The exam guide calls tool use with a JSON schema the most reliable way to get schema-compliant output. You define the schema above as a tool, Claude responds with a tool_use content block, and you read the structured data from that block's input. No parsing JSON out of prose, so no syntax errors.
The part people miss is tool_choice:
| Setting | What Claude does | Use it when |
|---|---|---|
{"type": "auto"} | May call a tool or reply in plain text | Conversational agents where text is a valid answer |
{"type": "any"} | Must call a tool, picks which one | Several extraction schemas exist and the document type is unknown |
{"type": "tool", "name": "extract_invoice"} | Must call that exact tool | One specific extraction has to run, for example before enrichment |
With auto, the model can answer "Here's the invoice data:" in text and your pipeline gets nothing to parse.
Few-shot examples for the hard cases
Schemas fix shape. They don't teach judgment. When instructions alone give inconsistent results, Task Statement 4.2 points to few-shot examples as the most effective fix. Two to four targeted examples is the usual range.
Pick examples that show the cases where the model goes wrong: an invoice with no date (output null), a receipt where the total appears only in a footer, a line item that could be hardware or services (output "unclear"). Examples of varied document layouts also cut down on empty extractions of required fields.
Validate, then retry with the error fed back
Tool use guarantees syntactic validity: the output parses and matches the schema. It does not guarantee semantic validity. Line items can fail to add up to the total. A shipping address can land in the billing field.
So validate in code after extraction. Extracting both stated_total and calculated_total makes the most common check trivial. When a check fails, send a follow-up request containing three things (Task Statement 4.4):
flowchart LR
A[Extract via forced tool] --> B{Validate in code}
B -->|pass| C[Store result]
B -->|fail| D[Retry: original document + failed output + specific errors]
D --> B
B -->|info absent from source| E[Return null or route to human review]
- The original document
- The failed extraction
- The specific validation errors, such as "line items sum to 1,180.00 but stated_total is 1,280.00"
A specific error gives the model something to correct. "Please try again" doesn't.
Know when to stop. Retries fix format and structure mistakes. They can't recover information that isn't in the source, for example a PO number that only exists in a separate document you didn't send. Accept the null or send it to a human.
Newer API versions also offer a strict structured-outputs mode that constrains generation to your schema. Check the current Claude docs for it. It still covers syntax only, so you need the semantic checks either way.
Try it
A pipeline extracts contract metadata and then runs an enrichment step that assumes metadata exists. About 3% of runs skip extraction: Claude replies with a text summary instead of calling extract_metadata. The request uses tool_choice: {"type": "auto"}. What's the best fix?
- A. Add "Always call the extract_metadata tool" to the system prompt
- B. Set
tool_choiceto{"type": "tool", "name": "extract_metadata"} - C. Parse the text summary with a regex when no tool call is returned
- D. Retry the request until a
tool_useblock appears
Answer: B. Forcing the named tool guarantees that extraction runs before enrichment. A is a prompt-level nudge that lowers the failure rate without removing it. C rebuilds the fragile text parsing that tool use exists to avoid. D wastes calls and still offers no guarantee.
Key takeaways
- Design the schema first: required only when always present, nullable when it may be missing, enums with
"other"and"unclear". - Use tool use with
input_schema, and force structure withtool_choiceset toanyor a named tool. - Use 2-4 few-shot examples for ambiguous cases and varied document layouts.
- Schema compliance is syntax. Check semantics (totals, field placement) in code.
- Retry with the document, the failed output and the specific error, and stop retrying when the data isn't in the source.
Frequently asked questions
Define a tool whose input_schema is your JSON schema and force it with tool_choice. Then read the structured data from the tool_use block instead of parsing text.
Usually because the field is required and the source doesn't contain it. Make the field nullable and show a few-shot example where the correct output is null.
No. It removes syntax and schema errors, not semantic ones like totals that don't add up. Those still need validation in code.
Good schemas pair with clear tool descriptions, and the same structured-data habit helps with long-context handoffs. Practice Domain 4 scenarios to test yourself on tool_choice and validation questions.