I have a table like this:
id title parent_id
1 a 0
2 b 0
3 c 1
4 d 2
5 e 1
6 f 3
7 g 3
and I need make a json to send to frontend. I dont know how to make this json from my table. here is some other information about my goal and code: node type :
type Node struct {
Id int64 `json:"id"'
Title string `json:"title"`
ParentId int64 `json:"parent_id"`
Children []Node `json:"children"`
}
I'm using sqlx to read from database to slice
And I need a json like this:
[
{
"id" : 1,
"title" : "a",
"parent_id" : 0,
"children" : [
{
"id" : 3,
"title" : "c",
"parent_id" : 1,
"children" .....
}
]
},
.
.
.
]
There is already a question similar to my question but the difference is that I'm reading nodes from mysql table not from console and also I need to marshal the tree to json
var items = select * from tbl order by parent_id;
Node.addChild = n=>this.children.add(n);
var root= new Node({Id:0, Parent:null, Title:'Root',Children:[]);
add(root, items, 0,0)
function add(tree,items, depth){
if(depth>100){
throw 'something';
}
var itemsOnThisLevel = items.where(item.parent_id==tree.id)
foreach(var item in itemsOnThisLevel){
var n = new Node(item);
tree.add(n);
add(n, items, depth+1);
}
}