Skip to main content

Module 09: Structured Outputs

Getting Claude to return structured JSON responses.

What You’ll Learn

  • Using JsonSchema to define output structure
  • Configuring structured outputs with CLIOptions
  • Parsing JSON responses with Jackson

Why Structured Outputs?

Instead of parsing free-form text, get Claude to return predictable JSON:

Defining a Schema

Use JsonSchema to define the expected output structure:

Using Structured Outputs

Structured outputs require CLIOptions with ClaudeSyncClient:

Nested Schemas

Define complex structures with arrays and nested objects:

JsonSchema Methods

JSON Types Reference

Note on Query API

The simplified QueryOptions class does not support jsonSchema. Use CLIOptions with ClaudeSyncClient for structured outputs.

Limitations

  • No strict enforcement: Claude attempts to match your schema but may occasionally produce invalid JSON or missing fields. Always validate the response.
  • Schema complexity: Deeply nested schemas (>3-4 levels) or schemas with many optional fields increase the chance of malformed output.
  • Error handling: When Claude fails to produce valid JSON, you receive raw text. Wrap parsing in try-catch:
  • No partial results: If Claude’s response is truncated (due to maxTokens), the JSON will be incomplete and unparseable.
  • Tool use interactions: When Claude uses tools during a structured output request, intermediate messages are unstructured. Only the final response follows the schema.

Source Code

View on GitHub

Running the Example

Next Module

Module 10: Multi-Turn Conversations - Building conversational applications with context.