我有一种情况,我必须将整个结构转换为 map 。
我知道我们有一个库structs.Map(s),它将结构转换为 map 。但是我想知道是否可以将struct内部的多个struct转换为map [string] interface。
例如我们下面
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)
}
这将产生如下结果,即再次为内部结构创建映射map[Description:this belong to A community
Moderators:[]
Name:A Sources:[map[SourceName:SourceA Region:[map[State1:State1 State2:] map[State1: State2:State2]]]]]
我的期望是只得到一个map [string] interface {}map[
Description:this belong to A community
Moderators:[]
Name:A
SourceName:SourceA
State1:State1
State2:State2
]
我创建单个映射的目的是将值与基于key的不同映射进行比较。根据不同的响应,我的结构也有所不同,所以我想有一张 map ,在这里我可以获取所有键值对以便于比较。如果有人对此有建议,请告诉我。
最佳答案
您可以使用 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{"[email protected]", "[email protected]"}
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)
}
playground关于dictionary - 如何将整个嵌套结构转换为 map ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/63577003/