首页 > 解决方案 > 如何重构数据

问题描述

我有这种格式的数据。

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 中传递数据的最佳方法是使用结构而不是映射之前有人告诉我。那是对的吗?

标签: 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)
}

推荐阅读