Guaranteed JSON Schema Compliance for Claude Code Output

Status Fixed / completed
Maintainer reply ✓ Yes — ashwin-ant
Activity 4 comments · opened Oct 7, 2025 · closed Nov 18, 2025
💡 Likely answer: A maintainer (ashwin-ant, collaborator) responded on this thread — see the highlighted reply below.

Preflight Checklist

  • [x] I have searched existing requests and this feature hasn't been requested yet
  • [x] This is a single feature request (not multiple features)

Problem Statement

Claude Code cannot guarantee output matches a specific JSON schema. --output-format json returns Claude Code's wrapper structure, with actual data nested inside:

{
  "messages": [...],
  "result": {
    "content": [{"type": "text", "text": "{\"countries\": [...]}"}]
  }
}

Users must extract and validate the nested JSON against their schema. Tool calling improves reliability but doesn't guarantee 100% schema compliance, requiring validation and error handling in production pipelines.

Proposed Solution

Add a --json-schema flag that enforces schema compliance via constrained decoding:

claude -p "List countries with capitals" \
  --output-format json \
  --json-schema countries.schema.json

The nested response content is guaranteed to match the provided JSON schema.

Alternative Solutions

  1. Tool calling enhancement: Add --strict-schema flag to existing tool calling mechanism
  2. New output format: --output-format strict-json that takes schema as input
  3. Configuration file: Schema definitions in .claude/schemas/ directory

Priority

High - Significant impact on productivity

Feature Category

CLI commands and flags

Use Case Example

Schema file (countries.schema.json):

{
  "type": "array",
  "items": {
    "type": "object",
    "required": ["country", "capital"],
    "properties": {
      "country": {"type": "string"},
      "capital": {"type": "string"}
    }
  }
}

Command:

claude -p "List 3 countries with capitals" \
  --output-format json \
  --json-schema countries.schema.json | jq '.result.content[0].text | fromjson'

Guaranteed output format:

[
  {"country": "France", "capital": "Paris"},
  {"country": "Germany", "capital": "Berlin"},
  {"country": "Japan", "capital": "Tokyo"}
]

Can pipe directly to databases, APIs, or processing scripts without validation.

Additional Context

Current workarounds:

  • Manual validation with libraries like json-repair
  • Retry loops with error handling
  • Careful prompting (unreliable)

Comparison:
OpenAI provides this via Structured Outputs with strict: true flag, guaranteeing 100% schema compliance at token generation level.

Related issues: #586, #2904, #3383

Benefits:

  • Eliminates validation code in production
  • Enables reliable CI/CD automation
  • Reduces error handling complexity

View original on GitHub ↗

4 Comments

thgaskell · 9 months ago

Structured outputs is now in public beta on the developer platform, so hopefully this means it will make it's way into Claude Code soon!

Announcement: https://claude.com/blog/structured-outputs-on-the-claude-developer-platform
Docs: https://docs.claude.com/en/docs/build-with-claude/structured-outputs

trevorprater · 9 months ago

SDK Use Case: Structured Outputs with Pydantic Integration

This feature would enable production-grade structured outputs support in the Claude Agent SDK for Python. We've implemented and validated the complete infrastructure, which is ready to integrate once CLI support is available.

Implementation Status

PR #328 contains production-ready SDK infrastructure:

  • ✅ Pydantic v1/v2 → JSON Schema conversion
  • ✅ Public API (output_format parameter)
  • ✅ Schema validation and cleaning
  • ✅ 151 tests passing, 0 mypy errors
  • Validated through Claude Code CLI with HTTP interception (confirmed via testing)

Link: https://github.com/anthropics/claude-agent-sdk-python/pull/328

Validated API Format

Through comprehensive testing, we've confirmed the correct schema format:

{
  "type": "json_schema",
  "schema": {
    "type": "object",
    "properties": { /* ... */ },
    "required": [...],
    "additionalProperties": false  # Required by API
  }
}

Current SDK Usage

from pydantic import BaseModel, Field
from claude_agent_sdk import query

class ProductInfo(BaseModel):
    sku: str = Field(description="Stock keeping unit")
    name: str
    price: float = Field(gt=0)
    in_stock: bool

# Per-query parameter
async for message in query(
    prompt="Extract: SKU-123, Widget, $29.99, in stock",
    output_format=ProductInfo  # Pydantic model or dict schema
):
    # Would receive schema-compliant JSON once CLI supports it
    print(message)

The SDK automatically:

  • Converts Pydantic models to JSON Schema
  • Adds required additionalProperties: false
  • Sets anthropic-beta: structured-outputs-2025-11-13 header
  • Validates schema format before use

Validation Results

We've validated the implementation through the Claude Code CLI (with HTTP interception):

  • ✅ API accepts anthropic-beta: structured-outputs-2025-11-13
  • ✅ API accepts schema format from SDK conversion
  • ✅ API returns structured JSON matching schema
  • ✅ Works with Claude Sonnet 4.5 (Haiku 4.5 not supported)
  • ✅ Requires API key authentication (OAuth not supported by beta)

Production-Ready Examples

The SDK includes sophisticated examples demonstrating:

  • E-commerce product extraction (3-level nesting, validators)
  • Legal contract analysis (4-level nesting, computed fields)
  • Research paper metadata (regex validators, citation tracking)
  • SaaS feature triage (priority scoring, business metrics)

Integration Path

Once CLI adds schema support, the integration flow would be:

  1. SDK generates JSON schema from Pydantic model
  2. SDK passes schema to CLI via the CLI's chosen mechanism
  3. CLI forwards schema to Messages API with appropriate beta header
  4. API returns structured JSON matching the schema
  5. SDK delivers type-safe response to user

The SDK is designed to integrate with whatever mechanism the CLI team implements for schema passing.

Ready to collaborate on implementation details or provide additional context.

---

References:

ashwin-ant collaborator · 9 months ago

This is available in 2.0.45 via --json-schema. The Agent SDK has also added support: https://docs.claude.com/en/docs/agent-sdk/structured-outputs

github-actions[bot] · 9 months ago

This issue has been automatically locked since it was closed and has not had any activity for 7 days. If you're experiencing a similar issue, please file a new issue and reference this one if it's relevant.