go - 如何将 interface{} 转换为 Golang 中的嵌套树

标签 go tree nested

传入的接口(interface){}会被转换为[]map[string]接口(interface){}。

原始数据类型是 []map[string]interface{} :

[
  {
    "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的if方法:

$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
}

我的英语不好。 只能通过代码和谷歌翻译的方式表达。 希望得到大家的帮助。

最佳答案

解决方案

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))
}

转到 https://play.golang.org/p/CMk1yhEOhd对其进行测试。

关于go - 如何将 interface{} 转换为 Golang 中的嵌套树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43265724/

相关文章:

go - 检测 JSON 文件是否有字段

Java:传递未实例化的对象引用如何工作?

java - 二叉搜索树无法将节点与空值进行比较

clojure - 功能性地遍历树

dictionary - Ansible:更改嵌套变量的默认值

python - 循环遍历嵌套字典值以填充第二个字典 - python

去编译错误?

postgresql - 不是用一对多关联创建的外键

docker - Docker镜像构建失败,出现 “COPY failed: no source files were specified”

Python嵌套循环和更新集