douchiwan1503 2017-04-06 21:04
浏览 44
已采纳

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

The incoming interface{} will be converted to []map[string]interface{}.

Raw data type is []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"
  }
]

Hope to get type for 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"
      }
    }
  }
]

if methods of 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 is not run:

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
}

my english is not good. only be expressed by way of code and google translation. Hope to get everyone's help.

  • 写回答

2条回答 默认 最新

  • doujiao3346 2017-04-08 10:24
    关注

    Solution

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

    Go to https://play.golang.org/p/CMk1yhEOhd to test it.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?