The Problem with Unstructured Output
By default, Claude responds in natural language. But your code needs structured data - JSON, arrays, specific formats.
# Ask for JSON explicitly
response = client.messages.create(
model="claude-sonnet-4-20250514",
max_tokens=1024,
system="Extract information as JSON. Return ONLY valid JSON, no other text.",
messages=[{"role": "user", "content": "Extract: John Smith, age 35, lives in NYC, works at Google"}]
)
# Returns: {"name": "John Smith", "age": 35, "city": "NYC", "company": "Google"}Using Tool Use for Guaranteed Structure
The most reliable way to get structured output is tool use (covered in depth in Module 05). You define a JSON Schema, and Claude fills it:
tools = [{
"name": "extract_person",
"description": "Extract person info",
"input_schema": {
"type": "object",
"properties": {
"name": {"type": "string"},
"age": {"type": "integer"},
"city": {"type": "string"}
},
"required": ["name"]
}
}]Key Takeaways
- This lesson covered structured data extraction: get json, not essays
- Apply these concepts in your own projects before moving on
- Refer back to this lesson when you encounter related challenges