1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
| package main
import ( "bytes" "encoding/json" "log" "os" )
type dataSource struct { ID string `json:"id"` Pid string `json:"pid"` }
type d struct { Level int8 `json:"level"` ID string `json:"id"` Pid string `json:"pid"` Children []d `json:"children"` }
var data = []*dataSource{ { ID: "1", Pid: "0", }, { ID: "2", Pid: "1", }, { ID: "3", Pid: "1", }, { ID: "4", Pid: "0", }, { ID: "5", Pid: "4", }, { ID: "6", Pid: "4", }, { ID: "7", Pid: "3", }, { ID: "8", Pid: "3", }, }
func handle(pid string, level int8) []d { var tree []d for _, v := range data { if v.Pid == pid { var children []d children = append(children, handle(v.ID, level+1)...) tree = append(tree, d{ Level: level, ID: v.ID, Pid: v.Pid, Children: children, }) } } return tree }
func main() { root := handle("0", 0) b, _ := json.Marshal(root)
var out bytes.Buffer err := json.Indent(&out, b, "", "\t")
if err != nil { log.Fatalln(err) }
out.WriteTo(os.Stdout) }
|