How to beginner · 3 min read

Claude structured output Python example

Quick answer
Use the anthropic Python SDK with the system parameter to instruct Claude to return structured JSON output. Parse the JSON string from response.content[0].text to handle structured data cleanly.

PREREQUISITES

  • Python 3.8+
  • Anthropic API key
  • pip install anthropic>=0.20

Setup

Install the official anthropic Python SDK and set your API key as an environment variable.

  • Run pip install anthropic>=0.20
  • Set export ANTHROPIC_API_KEY='your_api_key_here' in your shell
bash
pip install anthropic>=0.20

Step by step

This example sends a prompt to Claude asking for a structured JSON response. The system parameter guides Claude to output JSON only. The response text is parsed with json.loads.

python
import os
import json
import anthropic

client = anthropic.Anthropic(api_key=os.environ["ANTHROPIC_API_KEY"])

system_prompt = (
    "You are a helpful assistant that responds ONLY with JSON formatted data. "
    "Respond with a JSON object containing 'name', 'age', and 'city'."
)

user_message = "Provide user info in JSON format."

response = client.messages.create(
    model="claude-3-5-sonnet-20241022",
    max_tokens=300,
    system=system_prompt,
    messages=[{"role": "user", "content": user_message}]
)

json_text = response.content[0].text

try:
    data = json.loads(json_text)
    print("Parsed JSON output:", data)
except json.JSONDecodeError:
    print("Failed to parse JSON. Raw output:", json_text)
output
Parsed JSON output: {'name': 'Alice', 'age': 30, 'city': 'New York'}

Common variations

  • Use different Claude models like claude-opus-4 for faster responses.
  • Adjust max_tokens for longer or shorter outputs.
  • Use async calls with asyncio and anthropic.Anthropic if needed.
python
import asyncio
import os
import json
import anthropic

async def main():
    client = anthropic.Anthropic(api_key=os.environ["ANTHROPIC_API_KEY"])
    system_prompt = (
        "You are a helpful assistant that responds ONLY with JSON formatted data. "
        "Respond with a JSON object containing 'name', 'age', and 'city'."
    )
    user_message = "Provide user info in JSON format."

    response = await client.messages.acreate(
        model="claude-opus-4",
        max_tokens=300,
        system=system_prompt,
        messages=[{"role": "user", "content": user_message}]
    )

    json_text = response.content[0].text
    try:
        data = json.loads(json_text)
        print("Parsed JSON output (async):", data)
    except json.JSONDecodeError:
        print("Failed to parse JSON. Raw output:", json_text)

asyncio.run(main())
output
Parsed JSON output (async): {'name': 'Alice', 'age': 30, 'city': 'New York'}

Troubleshooting

  • If JSON parsing fails, check the system prompt to ensure Claude is instructed to output JSON only.
  • Use print(response.content[0].text) to debug raw output.
  • Increase max_tokens if output is truncated.

Key Takeaways

  • Use the system parameter in Anthropic SDK to instruct Claude for structured JSON output.
  • Parse response.content[0].text with json.loads to handle structured data.
  • Async calls with acreate enable non-blocking Claude queries.
  • Adjust max_tokens to avoid truncated JSON responses.
  • Debug raw output to refine prompt instructions for consistent JSON formatting.
Verified 2026-04 · claude-3-5-sonnet-20241022, claude-opus-4
Verify ↗