Reputation: 599
I have a little issue creating this kind of tree structure in go.
{
"uuid": "uuid1",
"label": "label1",
"children": [{
"uuid": "uuid2",
"label": "label2",
"children": [{
"uuid": "uuid3",
"label": "label3",
"children": [{
"uuid": "uuid5",
"label": "label5",
},{
"uuid": "uuid7",
"label": "label7",
}]
},
"uuid": "uuid4",
"label": "label4",
"children": [{
"uuid": "uuid6",
"label": "label6",
}]
}]
}]}
I tried it with maps, but I have a problem creating it. The map I came up with looked like this:
Tree := make(map[string]map[string]map[string][]interface{})
The data would come from a database where every row looks something like this:
uuid | level1 | level2 | level3 | level4 |
---|---|---|---|---|
uuid5 | label5 | label3 | label2 | label1 |
uuid7 | label7 | label3 | label2 | label1 |
I hope someone can help me with this, got some headache from that already.
Upvotes: 0
Views: 638
Reputation: 165
Well,I think you paste the text of tree structure is error。 I adjust it,like this:
{
"uuid": "uuid1",
"label": "label1",
"children": [
{
"uuid": "uuid2",
"label": "label2",
"children": [
{
"uuid": "uuid3",
"label": "label3",
"children": [
{
"uuid": "uuid4",
"label": "label4"
}
]
}
]
}
]
}
I offer to use Go Struct, not map。
Before two months,I found a nice website, which can help to convert to Go struct from JSON format struct。
Before Convert:
type AutoGenerated struct {
UUID string `json:"uuid"`
Label string `json:"label"`
Children []struct {
UUID string `json:"uuid"`
Label string `json:"label"`
Children []struct {
UUID string `json:"uuid"`
Label string `json:"label"`
Children []struct {
UUID string `json:"uuid"`
Label string `json:"label"`
} `json:"children"`
} `json:"children"`
} `json:"children"`
}
Upvotes: 0
Reputation: 1270
As suggested by Jason, your json tree structure is wrong. I would suggest using online tools for validating json's.
Apart from that, All you need to do here is to define a struct for your tree structure like below. Here is the working example on playground with your json document.
type Node struct {
UUID string `json:"uuid"`
Label string `json:"label"`
Childrens []Node `json:"children"`
}
We prefer using structs
over maps
as they are typesafe. Go being a strongly typed language, using structs is more idiomatic.
Upvotes: 3