传入接口{}将转换为[] 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的方法:
$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
}
我的英语不好。 只能通过代码和谷歌翻译来表达。 希望得到大家的帮助。
答案 0 :(得分: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))
}
答案 1 :(得分:0)
一个好的开始是介绍
type Post struct {
ID int
Name string
ParentID int
Depth int
Path string
}
var posts []Post
并使用包encoding/json
将Unmarshal
JSON列表添加到Go中的变量。