简体   繁体   English

Go:是否可以编组循环的 json

[英]Go: is it possible to marshal a cycled json

I'm coding Go to create a Circular Singly Linked List: https://www.geeksforgeeks.org/circular-singly-linked-list-insertion/我正在编写代码去创建一个循环单链表: https : //www.geeksforgeeks.org/circular-singly-linked-list-insertion/

Here is my code:这是我的代码:

type Node struct {
    Name string `json:"name"`
    Next *Node  `json:"next"`
}

func main() {
    n1 := Node{Name: "111", Next: nil}
    n2 := Node{Name: "222", Next: &n1}
    n3 := Node{Name: "333", Next: &n2}
    n1.Next = &n3
}

However, when I try to marshal, I get an error: json: unsupported value: encountered a cycle via *main.Node但是,当我尝试编组时,出现错误: json: unsupported value: encountered a cycle via *main.Node

res, err := json.Marshal(n1)
if err != nil {
    fmt.Println(err)
} else {
    fmt.Println(res)
}

Well, I understand why I get this error.好吧,我明白为什么我会收到这个错误。 So I want to know if there is some method to allow me to convert the struct of Node to JSON.所以我想知道是否有一些方法可以让我将Node的结构转换为JSON。

From the documentation of encoding/json.Marshal来自 encoding/json.Marshal 的文档

JSON cannot represent cyclic data structures and Marshal does not handle them. JSON 不能表示循环数据结构,Marshal 不处理它们。 Passing cyclic structures to Marshal will result in an error.将循环结构传递给 Marshal 会导致错误。

The main part is "JSON cannot represent cyclic data structures" so the answer is a clear No: It is not possible to have JSON which represents your value.主要部分是“JSON 不能表示循环数据结构”,所以答案是明确的“否”:不可能有 JSON 来表示您的价值。 You must redesign.你必须重新设计。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM