go
type_error
ai_generated
true
error: json: cannot unmarshal object into Go value of type map[int]string
ID: go/encoding-json-unmarshal-into-map-with-non-string-key
80%Fix Rate
82%Confidence
0Evidence
2024-02-25First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 1.20 | active | — | — | — |
| 1.21 | active | — | — | — |
Root Cause
JSON object keys are always strings, but the target map has non-string key type like int.
generic中文
JSON对象键始终是字符串,但目标映射具有非字符串键类型如int。
Workarounds
-
90% success Use map[string]interface{} and then convert keys
var raw map[string]interface{} json.Unmarshal(data, &raw) result := make(map[int]string) for k, v := range raw { i, _ := strconv.Atoi(k) result[i] = v.(string) }
Dead Ends
Common approaches that don't work:
-
Using string key map and converting manually
40% fail
Works but inefficient; use map[string]interface{} and convert.