go runtime_error ai_generated true

panic: json: infinite recursion (invalid cycle)

ID: go/encoding-json-marshal-infinite-recursion

Also available as: JSON · Markdown · 中文
80%Fix Rate
81%Confidence
0Evidence
2025-07-20First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
1.20 active
1.21 active

Root Cause

A struct has a circular reference that causes json.Marshal to recurse infinitely, leading to a stack overflow.

generic

中文

结构体存在循环引用,导致json.Marshal无限递归,最终栈溢出。

Workarounds

  1. 90% success Implement json.Marshaler to break cycles or use pointer indirection
    type Node struct {
        Value int
        Next  *Node
    }
    func (n *Node) MarshalJSON() ([]byte, error) {
        if n == nil { return json.Marshal(nil) }
        return json.Marshal(struct{ Value int }{Value: n.Value})
    }

Dead Ends

Common approaches that don't work:

  1. Adding a depth counter to break recursion 50% fail

    May still panic if depth exceeded; better to use custom marshaler.