【问题标题】:How to convert an interface{} to nested tree in Golang如何在 Golang 中将 interface{} 转换为嵌套树
【发布时间】:2017-04-06 21:04:14
【问题描述】:

传入的接口{}将被转换为[]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"
      }
    }
  }
]

if 的 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
}

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

【问题讨论】:

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

标签: go tree nested


【解决方案1】:

解决方案

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进行测试。

【讨论】:

    【解决方案2】:

    一个好的开始是介绍

    type Post struct {
      ID int
      Name string
      ParentID int
      Depth int
      Path string
    }
    
    var posts []Post
    

    并使用包 encoding/jsonUnmarshal 的 JSON 列表到 Go 中的一个变量。

    【讨论】:

      猜你喜欢
      • 2017-10-17
      • 2014-12-30
      • 1970-01-01
      • 2017-01-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-22
      相关资源
      最近更新 更多