JSON Marshal Cycle Detection
encoding/json detects reference cycles while marshaling and returns an unsupported-value error, so flat DTOs keep nested graphs serializable.
Code
package main
import (
"encoding/json"
"fmt"
"strings"
)
type Node struct {
Name string
Next *Node
}
func main() {
a := &Node{Name: "head"}
b := &Node{Name: "tail"}
a.Next = b
b.Next = a // cycle: a direct Marshal would recurse forever; encoding/json detects it mid-traversal and returns an error
_, err := json.Marshal(a)
fmt.Println("cycle error:", err != nil, strings.Contains(err.Error(), "cycle"))
// fix: flatten the graph into an acyclic DTO, then serialize
flat := struct {
Name string `json:"name"`
Next string `json:"next"`
}{Name: a.Name, Next: a.Next.Name}
out, err := json.Marshal(flat)
fmt.Println("flat json:", string(out), "err:", err)
}Inside the snippet
JSON Marshal Cycle Detection is built around the function main.
Points of care
- Every call resolves to a built-in API — no package manager ever runs.
Putting it to use
Signature: func main()
The run emits 2 labeled sections — cycle error:, flat json: — one per step.
The core lines of the flow
b.Next = a // cycle: a direct Marshal would recurse forever; encoding/json detects it mid-traversal and returns an error
Interactive Tools for This Topic
ASCII Table ReferenceLook up any ASCII code point 0-127 by decimal, hex, or character and see the binary, octal, and control-name view.ASCII85 EncoderEncode and decode ASCII85 (Base85), the Adobe variant with z zero-compression, handling arbitrary bytes and Unicode.Base32 Encoder & DecoderEncode and decode RFC 4648 Base32 with padding, fully UTF-8 safe so Unicode text round-trips without corruption. Nothing leaves your browser.Base45 Encoder and DecoderEncode and decode text with the Base45 alphabet defined in RFC 9285, with UTF-8 support, padding-free output, and clear validation errors.
FAQ
- What does JSON Marshal Cycle Detection print when run?
- The script runs standalone; its 2 labeled outputs include `cycle error:`, `flat json:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.