Dynamic JSON Keys to Go map Types
Convert JSON objects with dynamic or unknown keys to Go map[string]interface{} and map[string]T types. Covers type assertions and iteration patterns.
Detailed Explanation
Handling Dynamic JSON Keys with Go Maps
When a JSON object has keys that are not known at compile time, you cannot define a struct. Instead, use Go's map types.
Example JSON
{
"metrics": {
"cpu_usage": 72.5,
"memory_usage": 85.3,
"disk_io": 45.1
},
"labels": {
"env": "production",
"region": "us-east-1",
"team": "backend"
}
}
Generated Go Struct
type AutoGenerated struct {
Metrics map[string]float64 `json:"metrics"`
Labels map[string]string `json:"labels"`
}
When Values Have Mixed Types
If values are not uniform, use map[string]interface{} (or map[string]any in Go 1.18+):
{
"settings": {
"theme": "dark",
"fontSize": 14,
"autoSave": true
}
}
type Config struct {
Settings map[string]interface{} `json:"settings"`
}
Type Assertions
When using interface{} values, you need type assertions to access the underlying type:
if theme, ok := config.Settings["theme"].(string); ok {
fmt.Println("Theme:", theme)
}
Iterating Over Maps
for key, value := range response.Metrics {
fmt.Printf("%s: %.1f\n", key, value)
}
Struct vs Map Decision
Use a struct when the keys are known and fixed. Use a map when keys are dynamic, user-defined, or vary between responses. In practice, many APIs combine both — fixed fields as struct fields and dynamic fields as a map.
Use Case
Monitoring dashboards, feature flag systems, and key-value stores return JSON with unpredictable keys. Go maps let you process these without knowing the exact key names at compile time.