如何将整个嵌套结构转换为映射

joe*_*123 1 struct dictionary go

我有一个场景,我必须将整个结构转换为地图。我知道我们有一个库 structs.Map(s) 它将把结构转换为映射。但我想知道是否有一种方法可以将结构内部的多个结构转换为 map[string] 接口。例如我们有下面的

package main

import (
    "log"

    "github.com/fatih/structs"
)

type Community struct {
    Name        string   `json:"name,omitempty"`
    Description string   `json:"description,omitempty"`
    Sources     []Source `json:"sources,omitempty"`
    Moderators  []string `json:"moderators,omitempty"`
}

type Source struct {
    SourceName string  `json:"sourceName,omitempty"`
    Region []State `json:"region,omitempty"`
}

type State struct {
    State1 string `json:"state1,omitempty"`
    State2 string `json:"state2,omitempty"`
}

func main() {

    compareData := Community{
        Name:        "A",
        Description: "this belong to A community",
        Sources: []Source{
            {
                SourceName: "SourceA",
                Region: []State{
                    {
                        State1: "State1",
                    },
                    {
                        State2: "State2",
                    },
                },
            },
        },
    }
    m := structs.Map(compareData)
    log.Println(m)
}
Run Code Online (Sandbox Code Playgroud)

这将给出如下结果,即它再次为内部结构创建映射

map[Description:this belong to A community 
Moderators:[] 
Name:A Sources:[map[SourceName:SourceA Region:[map[State1:State1 State2:] map[State1: State2:State2]]]]]
Run Code Online (Sandbox Code Playgroud)

我的期望是只得到一个 map[string]interface{}

map[
Description:this belong to A community 
Moderators:[] 
Name:A 
SourceName:SourceA 
State1:State1 
State2:State2
]
Run Code Online (Sandbox Code Playgroud)

我创建单个映射的目的是根据 key 将值与不同的映射进行比较。我的结构也根据不同的响应而变化,所以我想要一个地图,我可以在其中获取所有键值对以便于比较。如果有人对此有建议,请告诉我。

ttr*_*asn 5

您可以使用mapstructure包。

使用示例:

package main

import (
    "fmt"
    "github.com/mitchellh/mapstructure"
)

func main() {

    type Emails struct {
        Mail []string
    }

    type Person struct {
        Name   string
        Age    int
        Emails Emails
        Extra  map[string]string
    }



    // This input can come from anywhere, but typically comes from
    // something like decoding JSON where we're not quite sure of the
    // struct initially.
    mails := []string{"foo@bar.com", "foo2@bar.com"}
    input := Person{
        Name:   "foo",
        Age:    25,
        Emails: Emails{Mail: mails},
        Extra:  map[string]string{"family": "bar"},
    }

    result := map[string]interface{}{}

    err := mapstructure.Decode(input, &result)
    if err != nil {
        panic(err)
    }

    fmt.Printf("%#v", result)
}


Run Code Online (Sandbox Code Playgroud)

操场