go
encoding_error
ai_generated
true
json: 不支持的类型:map[int]string
json: unsupported type: map[int]string
ID: go/json-marshal-error-unsupported-type
90%修复率
87%置信度
1证据数
2024-01-10首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| go1.19 | active | — | — | — |
| go1.20 | active | — | — | — |
| go1.21 | active | — | — | — |
| go1.22 | active | — | — | — |
根因分析
尝试编组键不是字符串的 Go 类型,JSON 格式不支持(JSON 对象键必须是字符串)。
English
Attempting to marshal a Go type with keys that are not strings, which JSON format does not support (JSON object keys must be strings).
官方文档
https://pkg.go.dev/encoding/json#Marshal解决方案
-
Convert map keys to strings before marshaling: `newMap := make(map[string]string); for k, v := range oldMap { newMap[fmt.Sprintf("%d", k)] = v }` -
Define a custom struct or use a slice of key-value pairs instead: `type Entry struct { Key int; Value string }` then marshal `[]Entry`.
无效尝试
常见但无效的做法:
-
90% 失败
MarshalIndent also calls json.Marshal internally; same error occurs.
-
60% 失败
Returning nil causes json.Marshal to serialize the value as 'null', not skip it; error still may occur depending on implementation.