Episode 04 · Lightweight · ~14 min · Intermediate
Learn how to get structured, typed JSON output from Claude every time — then unmarshal it directly into Go structs for safe downstream processing.
- Structured output via system prompts — crafting a system prompt that constrains Claude to return only valid JSON, with no markdown fences or prose
- Defining Go structs as extraction targets — using JSON struct tags to give Claude a clear schema to match
- Safe JSON unmarshalling — using
encoding/jsonto decode Claude's response directly into typed Go structs - Practical extraction examples — a
Personrecord (name, age, occupation, summary) and aMovieReviewwith nested slice fields (pros, cons)
export ANTHROPIC_API_KEY=your_api_key_here
go run main.go=== Extracted Person ===
Name: Dr. Sarah Chen
Age: 38
Occupation: Neuroscientist
Summary: Dr. Sarah Chen is a neuroscientist at the Karolinska Institute who studies memory consolidation during sleep.
=== Extracted Movie Review ===
Title: Dune: Part Two
Rating: 9/10
Sentiment: positive
Pros:
+ Stunning cinematography
+ Hypnotic score by Hans Zimmer
+ Zendaya's expanded screen time
+ Exceptional direction by Denis Villeneuve
Cons:
- Rushed political subtext in the third act
- Underwritten minor characters
const extractionSystemPrompt = "You are a data extraction assistant. Always respond with valid JSON only, no markdown, no explanation. Match the exact schema requested."This single system prompt is the foundation of the approach. It instructs Claude to skip all prose and return only the JSON object you need.
for _, block := range msg.Content {
switch v := block.AsAny().(type) {
case anthropic.TextBlock:
return v.Text, nil
}
}We type-switch on block.AsAny() to safely extract the text content from Claude's response.
var person Person
if err := json.Unmarshal([]byte(raw), &person); err != nil {
return fmt.Errorf("failed to unmarshal person: %w", err)
}Standard encoding/json — no special library needed.
| # | Title |
|---|---|
| 01 | Getting Started with the Claude API in Go |
| 02 | Streaming Responses from Claude in Go |
| 03 | Multi-Turn Conversations with Claude in Go |
| 04 | Structured JSON Output from Claude in Go |
| 05 | Tool Use with Claude in Go (coming soon) |