go - 如何重构数据
问题描述
我有这种格式的数据。
type PartsInfo struct {
Parts map[string]struct {
City string `yaml:"city"`
Services map[string]struct {
Disabled bool `yaml:"disabled"`
} `yaml:"services"`
} `yaml:"parts"`
}
我想将其转换为这种格式:
map[service]map[city][]parts
只需要添加未禁用状态服务。我一直在尝试不同的组合,但无法按照我想要的方式得到它。
我想我不确定的一件事是目标格式。我应该使用这种map[service]map[city][]parts
格式,还是结构更好?我不知道怎么做,但是在 go 中传递数据的最佳方法是使用结构而不是映射之前有人告诉我。那是对的吗?
解决方案
这是你想要的吗?</p>
去游乐场: https: //play.golang.org/p/N8mkD5pt1pD
package main
import "fmt"
type PartitionData struct {
Partitions map[string]Partition `yaml:"parts"`
}
type Partition struct {
City string `yaml:"city"`
Services map[string]map[string]struct {
Disabled bool `yaml:"disabled"`
} `yaml:"services"`
}
var testData = PartitionData{
Partitions: map[string]Partition{
"partition1": {City: "c1", Services: map[string]map[string]struct{
Disabled bool `yaml:"disabled"`
}{
"service1":{
"1":{
Disabled: true,
},
"2":{
Disabled: true,
},
},
"service2":{
"1":{
Disabled: true,
},
"2":{
Disabled: true,
},
},
}},
"partition2": {City: "c1", Services: map[string]map[string]struct{
Disabled bool `yaml:"disabled"`
}{
"service1":{
"1":{
Disabled: true,
},
"2":{
Disabled: true,
},
},
"service2":{
"1":{
Disabled: true,
},
"2":{
Disabled: true,
},
},
}},
},
}
func main() {
res:= make(map[string]map[string][]Partition)
for _,part := range testData.Partitions{
for serviceName :=range part.Services{
if _,found := res[serviceName];!found {
res[serviceName] = make(map[string][]Partition)
}
if _,found := res[serviceName][part.City];!found {
res[serviceName][part.City] = make([]Partition,0)
}
res[serviceName][part.City] = append(res[serviceName][part.City], part)
}
}
fmt.Println(res)
}
推荐阅读
- email - 当地址为空时,电子邮件是否会引发异常
- gitlab-ci - 如何在 gitlab-ci docker 容器中使用 docker-py 获取 docker 客户端?
- jquery - 附加容器时按 id 隐藏每个元素
- asterisk - 为什么在 yocto 星号的最终图像中不可用?
- c# - Xamarin-Android 和 UWP 之间的蓝牙连接
- html - 网站顶部的黑条 - 仅在 Firefox 上
- css - 下拉内容纯 CSS
- gettext - 在 Poedit 的 PO 文件中,如何提供关键字列表,以便为每个关键字自动提取评论?
- c# - 如何使用 VSTS 构建过程自动增加 nuget 包版本?
- tfs - “单元测试适配器抛出异常:无法加载一种或多种请求的类型。检索 LoaderExceptions 属性以获取更多信息”