如何在Golang中将接口{}转换为嵌套树

如何在Golang中将接口{}转换为嵌套树,go,tree,nested,Go,Tree,Nested,传入接口{}将转换为[]映射[字符串]接口{} 原始数据类型为[]映射[字符串]接口{}: [ { "ID": 1, "Name": "Root", "ParentID": 0, "Path": "Root" }, { "ID": 2, "Name": "Ball", "ParentID": 1, "Path": "Root/Ball" }, { "ID": 3, "Name": "Foot",

传入接口{}将转换为[]映射[字符串]接口{}

原始数据类型为[]映射[字符串]接口{}:

[
  {
    "ID": 1,
    "Name": "Root",
    "ParentID": 0,
    "Path": "Root"
  },
  {
    "ID": 2,
    "Name": "Ball",
    "ParentID": 1,
    "Path": "Root/Ball"
  },
  {
    "ID": 3,
    "Name": "Foot",
    "ParentID": 2,
    "Depth": 2,
    "Path": "Root/Ball/Foot"
  }
]
希望获得json的类型:

[
  {
    "ID": 1,
    "Name": "Root",
    "ParentID": 0,
    "Path": "Root",
    "Child": {
      "ID": 2,
      "Name": "Ball",
      "ParentID": 1,
      "Path": "Root/Ball",
      "Child": {
        "ID": 3,
        "Name": "Foot",
        "ParentID": 2,
        "Depth": 2,
        "Path": "Root/Ball/Foot"
      }
    }
  }
]
如果使用php的方法:

$data = Raw data is array()...

$result = array();

$temp = array();

foreach($data as $item) {
    if($item['ParentID'] == 0) {
        $result[$item['ID']] = $item;
        $temp[$item['ID']] =& $result[$item['ID']];
    }else {
        $temp[$item['ParentID']][$item['ID']] = $item;
        $temp[$item['ID']] =& $temp[$item['ParentID']][$item['ID']];
    }
}

return $result
golang未运行:

func tree(array interface{}) map[int]*[]map[string]interface{} {

    results := make(map[int]*map[string]interface{})
    temp := make(map[int]map[string]*map[string]interface{})
    for _, item := range maps(array) {

        id := int(item["ID"].(float64))
        pid := int(item["ParentID"].(float64))

        if pid == 0 {
            results[id] = item
            temp[id]["c"] = &results[id]
        } else {
            temp[pid]["c"] = item
            temp[id] = &temp[pid]["c"]
        }
    }
    return results
}

func maps(val interface{}) []map[string]interface{} {
    if b, err := json.Marshal(val); err == nil {
        var maps []map[string]interface{}
        json.Unmarshal(b, &maps)
        return maps
    }
    return nil
}
我的英语不好。 只能通过代码和谷歌翻译的方式表达。
希望能得到大家的帮助。

一个好的开始就是介绍

type Post struct {
  ID int
  Name string
  ParentID int
  Depth int
  Path string
}

var posts []Post

并使用package
encoding/json
将json列表转换为Go中的变量。

解决方案

package main

import (
    "encoding/json"
    "fmt"
)

var indata string = `[
  {
    "ID": 1,
    "Name": "Root",
    "ParentID": 0,
    "Path": "Root"
  },
  {
    "ID": 2,
    "Name": "Ball",
    "ParentID": 1,
    "Path": "Root/Ball"
  },
  {
    "ID": 3,
    "Name": "Foot",
    "ParentID": 2,
    "Depth": 2,
    "Path": "Root/Ball/Foot"
  }
]`

type Node struct {
    ID       int
    Name     string
    ParentID int
    Depth    int
    Path     string
    Child    *Node
}

func main() {
    nodes := []Node{}

    err := json.Unmarshal([]byte(indata), &nodes)
    if err != nil {
        panic(err)
    }

    m := make(map[int]*Node)
    for i, _ := range nodes {
        //fmt.Printf("Setting m[%d] = <node with ID=%d>\n", n.ID, n.ID)
        m[nodes[i].ID] = &nodes[i]
    }

    for i, n := range nodes {
        //fmt.Printf("Setting <node with ID=%d>.Child to <node with ID=%d>\n", n.ID, m[n.ParentID].ID)
        if m[n.ParentID] != nil {
            m[n.ParentID].Child = &nodes[i]
        }
    }

    outdata, err := json.Marshal(m[1])
    if err != nil {
        panic(err)
    }

    fmt.Println(string(outdata))
}
主程序包
进口(
“编码/json”
“fmt”
)
var indata字符串=`[
{
“ID”:1,
“名称”:“根”,
“ParentID”:0,
“路径”:“根”
},
{
“ID”:2,
“名称”:“球”,
“家长ID”:1,
“路径”:“根/球”
},
{
“ID”:3,
“名称”:“脚”,
“家长ID”:2,
“深度”:2,
“路径”:“根/球/脚”
}
]`
类型节点结构{
ID int
名称字符串
父ID整数
深度整数
路径字符串
子节点*
}
func main(){
节点:=[]节点{}
err:=json.Unmarshal([]字节(indata),&节点)
如果错误!=零{
恐慌(错误)
}
m:=make(映射[int]*节点)
对于i,z:=范围节点{
//fmt.Printf(“设置m[%d]=\n”,n.ID,n.ID)
m[nodes[i].ID]=&nodes[i]
}
对于i,n:=范围节点{
//fmt.Printf(“将.Child设置为\n”,n.ID,m[n.ParentID].ID)
如果m[n.ParentID]!=nil{
m[n.ParentID].Child=&nodes[i]
}
}
outdata,err:=json.Marshal(m[1])
如果错误!=零{
恐慌(错误)
}
fmt.Println(字符串(输出数据))
}

去测试它。

请显示一些努力。我们不是来为你编码的。您必须编写代码,我们会帮助您解决途中遇到的任何问题。@nemo对不起,是我的错。您为什么在PHP中使用
=&
?@md2perpe这不是递归,通过指针进行数据处理。PHP没有指针。PHP有参考资料。PHP还有“写时复制”功能,这意味着如果您执行了
$x=$y
,则
$y
不会被克隆,而只是被引用,直到有东西写入
$y
(例如
$y['name']=“Charlie”
)。