go
encoding_error
ai_generated
true
json: invalid recursive type: type MyStruct has recursive JSON method
ID: go/json-marshal-infinite-recursion
90%Fix Rate
85%Confidence
1Evidence
2023-07-12First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| Go 1.15 | active | — | — | — |
| Go 1.16 | active | — | — | — |
| Go 1.17 | active | — | — | — |
| Go 1.18 | active | — | — | — |
| Go 1.19 | active | — | — | — |
| Go 1.20 | active | — | — | — |
| Go 1.21 | active | — | — | — |
| Go 1.22 | active | — | — | — |
| Go 1.23 | active | — | — | — |
Root Cause
A custom MarshalJSON or UnmarshalJSON method on a type calls json.Marshal or json.Unmarshal on itself, causing infinite recursion.
generic中文
类型上的自定义 MarshalJSON 或 UnmarshalJSON 方法对自身调用 json.Marshal 或 json.Unmarshal,导致无限递归。
Official Documentation
https://pkg.go.dev/encoding/json#MarshalerWorkarounds
-
95% success Define an alias type (type MyStructAlias MyStruct) and marshal the alias instead of the original type
Define an alias type (type MyStructAlias MyStruct) and marshal the alias instead of the original type
-
90% success Use a raw byte slice or map[string]interface{} for manual marshaling without calling json.Marshal on self
Use a raw byte slice or map[string]interface{} for manual marshaling without calling json.Marshal on self -
85% success Implement MarshalJSON by calling json.Marshal on a temporary struct that mirrors the fields without the recursive method
Implement MarshalJSON by calling json.Marshal on a temporary struct that mirrors the fields without the recursive method
中文步骤
Define an alias type (type MyStructAlias MyStruct) and marshal the alias instead of the original type
Use a raw byte slice or map[string]interface{} for manual marshaling without calling json.Marshal on selfImplement MarshalJSON by calling json.Marshal on a temporary struct that mirrors the fields without the recursive method
Dead Ends
Common approaches that don't work:
-
95% fail
Both functions call the same MarshalJSON method; recursion persists.
-
70% fail
Loses custom serialization behavior; data may be serialized incorrectly.
-
80% fail
json package detects recursion before runtime depth limit; counter doesn't prevent detection.