go encoding_error ai_generated true

json: invalid recursive type: type MyStruct has recursive JSON method

ID: go/json-marshal-infinite-recursion

Also available as: JSON · Markdown · 中文
90%Fix Rate
85%Confidence
1Evidence
2023-07-12First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
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#Marshaler

Workarounds

  1. 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
  2. 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
  3. 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

中文步骤

  1. Define an alias type (type MyStructAlias MyStruct) and marshal the alias instead of the original type
  2. Use a raw byte slice or map[string]interface{} for manual marshaling without calling json.Marshal on self
  3. Implement 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:

  1. 95% fail

    Both functions call the same MarshalJSON method; recursion persists.

  2. 70% fail

    Loses custom serialization behavior; data may be serialized incorrectly.

  3. 80% fail

    json package detects recursion before runtime depth limit; counter doesn't prevent detection.