JSON Marshal Cycle Detection

encoding/json detects reference cycles while marshaling and returns an unsupported-value error, so flat DTOs keep nested graphs serializable.

GoData Integrity

Code

gosnippet
31 lines
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

FAQ

What does JSON Marshal Cycle Detection print when run?
The script runs standalone; its 2 labeled outputs include `cycle error:`, `flat json:`.