Skip to content

Latest commit

 

History

History

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 
 
 
 
 
 
 

README.md

04 — Structured JSON Output from Claude in Go

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.

What We Cover

  • 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/json to decode Claude's response directly into typed Go structs
  • Practical extraction examples — a Person record (name, age, occupation, summary) and a MovieReview with nested slice fields (pros, cons)

Running the Example

export ANTHROPIC_API_KEY=your_api_key_here
go run main.go

Expected Output

=== 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

Key Concepts

The System Prompt

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.

Reading the Response

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.

Unmarshalling into a Typed Struct

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.

Series

# 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)