Structured Output via tool_use & JSON Schemas
How to use tool_use with JSON schemas to guarantee syntactically valid structured output from Claude. Covers tool_choice modes, schema design patterns (nullable fields, enum + other), and the critical distinction between syntax errors and semantic errors.
Quick Reference
- →tool_use with JSON schemas is the most reliable method for structured output from Claude
- →tool_choice: 'auto' lets Claude decide whether to use tools; 'any' forces tool use; {type:'tool', name:'X'} forces a specific tool
- →Strict schemas eliminate syntax/format errors but NOT semantic errors (e.g., line items that don't sum to total)
- →Use nullable fields (type: ['string', 'null']) to prevent fabrication of missing data
- →The enum + 'other' + detail field pattern handles extensible categories cleanly
- →required array controls which fields Claude MUST provide vs which are optional
- →tool_use output is always valid JSON -- no need to parse or handle JSON syntax errors
- →Schema descriptions act as inline prompt engineering -- use them to clarify field semantics
- →For extraction tasks, tool_use outperforms asking Claude to 'output JSON' in a text response
- →Exam Scenario 6 (Structured Data Extraction) heavily tests tool_use schema design
Why tool_use Beats 'Output JSON' Instructions
There are three ways to get structured data from Claude: (1) ask it to output JSON in a text response, (2) use the system prompt to enforce JSON format, or (3) use tool_use with a JSON schema. Only option 3 guarantees syntactically valid output.
| Method | Syntax guarantee | Schema validation | Semantic guarantee | Reliability |
|---|---|---|---|---|
| 'Please output JSON' | No -- can include markdown, prose | No | No | ~70% |
| System prompt JSON mode | Better -- usually valid JSON | No -- may omit fields | No | ~90% |
| tool_use with schema | Yes -- always valid JSON matching schema | Yes -- required fields enforced | No -- values can still be wrong | ~99.9% |
This is one of the most tested distinctions on the exam. A tool_use schema guarantees the output is valid JSON with the correct field names and types. It does NOT guarantee that the values are correct. Line items might not sum to the total. A vendor name might be extracted from the wrong part of the document. Schema validation and semantic validation are separate concerns.
Force structured output by defining a tool schema and using tool_choice