go
encoding_error
ai_generated
true
json: unsupported type: map[int]string
ID: go/json-marshal-error-unsupported-type
90%Fix Rate
87%Confidence
1Evidence
2024-01-10First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| go1.19 | active | — | — | — |
| go1.20 | active | — | — | — |
| go1.21 | active | — | — | — |
| go1.22 | active | — | — | — |
Root Cause
Attempting to marshal a Go type with keys that are not strings, which JSON format does not support (JSON object keys must be strings).
generic中文
尝试编组键不是字符串的 Go 类型,JSON 格式不支持(JSON 对象键必须是字符串)。
Official Documentation
https://pkg.go.dev/encoding/json#MarshalWorkarounds
-
95% success Convert map keys to strings before marshaling: `newMap := make(map[string]string); for k, v := range oldMap { newMap[fmt.Sprintf("%d", k)] = v }`
Convert map keys to strings before marshaling: `newMap := make(map[string]string); for k, v := range oldMap { newMap[fmt.Sprintf("%d", k)] = v }` -
90% success Define a custom struct or use a slice of key-value pairs instead: `type Entry struct { Key int; Value string }` then marshal `[]Entry`.
Define a custom struct or use a slice of key-value pairs instead: `type Entry struct { Key int; Value string }` then marshal `[]Entry`.
中文步骤
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`.
Dead Ends
Common approaches that don't work:
-
90% fail
MarshalIndent also calls json.Marshal internally; same error occurs.
-
60% fail
Returning nil causes json.Marshal to serialize the value as 'null', not skip it; error still may occur depending on implementation.