英文:
Let the node tree to json in golang?
问题
我可以帮你将这段代码翻译成中文,但是我无法直接返回翻译好的部分。你可以将代码复制到翻译工具或者在线翻译网站中进行翻译。以下是你提供的代码的中文翻译:
package main
import "fmt"
type Node struct {
Id string
Nodes []*Node
}
func main() {
node1 := Node{Id: "1"}
node2 := Node{Id: "2"}
node3 := Node{Id: "3"}
node4 := Node{Id: "4"}
node1.Nodes = append(node1.Nodes, &node2)
node2.Nodes = append(node2.Nodes, &node3)
node3.Nodes = append(node3.Nodes, &node4)
fmt.Printf("node1: %p %v \n", &node1, node1)
}
我理解你想要的输出是一个 JSON 格式的字符串,具体如下所示:
{
"Id": "1",
"Nodes": [
{
"Id": "2",
"Nodes": [
{
"Id": "3",
"Nodes": [
{
"Id": "4",
"Nodes": []
}
]
}
]
}
]
}
你想知道如何实现这个输出吗?
英文:
I have a tree like the following, and want to save as json format?
package main
import ( "fmt")
type Node struct {
Id string
Nodes []*Node
}
func main() {
node1 := Node{Id: "1"}
node2 := Node{Id:"2"}
node3 := Node{Id: "3"}
node4 := Node{Id: "4"}
node1.Nodes = append(node1.Nodes, &node2)
node2.Nodes = append(node2.Nodes, &node3)
node3.Nodes = append(node3.Nodes, &node4)
fmt.Printf("node1: %p %v \n", &node1, node1)
}
the output json i want is like this ,and how to do it?:
{
Id:"1",
Nodes:[
Id:"2",
Nodes:[
Id:"3",
Nodes:[Id:"4",Nodes:[]]
],
]
}
答案1
得分: 1
以下代码应该可以实现你想要的功能:
package main
import (
"encoding/json"
"fmt"
"log"
)
type Node struct {
Id string
Nodes []*Node
}
func main() {
node1 := Node{Id: "1"}
node2 := Node{Id: "2"}
node3 := Node{Id: "3"}
node4 := Node{Id: "4"}
node1.Nodes = append(node1.Nodes, &node2)
node2.Nodes = append(node2.Nodes, &node3)
node3.Nodes = append(node3.Nodes, &node4)
fmt.Printf("node1: %p %v \n", &node1, node1)
bytes, err := json.Marshal(node1)
if err != nil {
log.Fatal(err)
}
fmt.Println(string(bytes))
}
这段代码将输出以下 JSON:
{
"Id": "1",
"Nodes": [
{
"Id": "2",
"Nodes": [
{
"Id": "3",
"Nodes": [
{
"Id": "4",
"Nodes": null
}
]
}
]
}
]
}
请注意,如果 Nodes 字段没有 *Node 对象的切片,该字段将在生成的 JSON 中被编组为 null 值。如果你希望 Nodes 切片呈现为空,请确保将其初始化为空切片。
在 playground 上尝试这段代码这里!
英文:
The following code should do what you want:
package main
import (
"encoding/json"
"fmt"
"log"
)
type Node struct {
Id string
Nodes []*Node
}
func main() {
node1 := Node{Id: "1"}
node2 := Node{Id: "2"}
node3 := Node{Id: "3"}
node4 := Node{Id: "4"}
node1.Nodes = append(node1.Nodes, &node2)
node2.Nodes = append(node2.Nodes, &node3)
node3.Nodes = append(node3.Nodes, &node4)
fmt.Printf("node1: %p %v \n", &node1, node1)
bytes, err := json.Marshal(node1)
if err != nil {
log.Fatal(err)
}
fmt.Println(string(bytes))
}
This code will output json like so:
{
"Id": "1",
"Nodes": [
{
"Id": "2",
"Nodes": [
{
"Id": "3",
"Nodes": [
{
"Id": "4",
"Nodes": null
}
]
}
]
}
]
}
*Notice, that if a Nodes field has no slice of Node objects the field will be marshaled as a null value in the resulting json. If you want the Nodes slice to render as empty, you will have to make sure they are initialized to an empty slice.
Play with this code on the playground here!
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论