go
type_error
ai_generated
true
错误:json:无法将对象解组为map[int]string类型的Go值
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%修复率
82%置信度
0证据数
2024-02-25首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 1.20 | active | — | — | — |
| 1.21 | active | — | — | — |
根因分析
JSON对象键始终是字符串,但目标映射具有非字符串键类型如int。
English
JSON object keys are always strings, but the target map has non-string key type like int.
解决方案
-
90% 成功率 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) }
无效尝试
常见但无效的做法:
-
Using string key map and converting manually
40% 失败
Works but inefficient; use map[string]interface{} and convert.