1 回答
TA贡献1834条经验 获得超8个赞
这是您想要做的吗? https://play.golang.org/p/AZNzQAwRhN0
其作用是构建一个按池对所有端口进行分组的映射。然后它循环遍历我标记的内容clusters
,并通过按值抓取匹配切片来将 的切片分配Port
给匹配的切片。Cluster
Pool
package main
import (
"encoding/json"
"fmt"
)
type Cluster struct {
ID string `json:"id"`
Name string `json:"name"`
Pool string `json:"pool"`
Ports []Port `json:"ports"`
}
type Port struct {
Name string `json:"name"`
Size int `json:"size"`
Pool string `json:"pool"`
Status string `json:"status"`
}
func main() {
var resources []Port
err := json.Unmarshal([]byte(resourceJSON), &resources)
if err != nil {
panic(err)
}
resourcesByPool := make(map[string][]Port)
for _, resource := range resources {
if _, ok := resourcesByPool[resource.Pool]; !ok {
resourcesByPool[resource.Pool] = []Port{}
}
resourcesByPool[resource.Pool] = append(resourcesByPool[resource.Pool], resource)
}
var clusters []Cluster
err = json.Unmarshal([]byte(clusterJSON), &clusters)
if err != nil {
panic(err)
}
for i := 0; i < len(clusters); i++ {
clusters[i].Ports = resourcesByPool[clusters[i].Pool]
}
out, err := json.MarshalIndent(clusters, "", " ")
if err != nil {
panic(err)
}
fmt.Println(string(out))
}
var (
clusterJSON = `[
{
"id": "device1",
"name": "dev1",
"pool": "pool1"
},
{
"id": "device2",
"name": "dev2",
"pool": "pool2"
}
]`
resourceJSON = `[
{
"name": "port1",
"size": 10,
"pool": "pool1",
"status": "active"
},
{
"name": "port2",
"size": 60,
"pool": "pool1",
"status": "active"
},
{
"name": "port3",
"size": 20,
"pool": "pool2",
"status": "down"
},
{
"name": "port8",
"size": 100,
"pool": "pool2",
"status": "active"
},
{
"name": "port10",
"size": 8000,
"pool": "pool1",
"status": "active"
}]`
)
- 1 回答
- 0 关注
- 111 浏览
添加回答
举报