JSON Encoding & Decoding in Go

From the Go cheat sheet · JSON · verified Jul 2026

JSON Encoding & Decoding

Marshal, Unmarshal, and struct tags for JSON

go
// Struct with JSON tags
type User struct {
    Name  string `json:"name"`
    Email string `json:"email,omitempty"`
    Age   int    `json:"age"`
}

// Encode (struct → JSON)
data, _ := json.Marshal(user)

// Decode (JSON → struct)
var u User
json.Unmarshal(data, &u)
📌 Use struct tags to control JSON field names and behavior
💡 omitempty skips zero-value fields, "-" excludes entirely
⚡ Use map[string]any for dynamic/unknown JSON structures
🎯 NewEncoder/NewDecoder for streaming — more efficient than Marshal/Unmarshal
Back to the full Go cheat sheet