我有一个 JSON 文件看起来像下面这样
{
"type": "Weekly",
"clients": [
"gozo",
"dva"
],
"sender": "no-reply@flowace.in",
"recipients": {
"gozo": [
"a@gmail.com",
"b@hotmail.com"
],
"dva": [
"c@gmail.com",
"d@hotmail.com"
]
},
"features": [
"Top5UsedApps",
"TimeSpentOnEachL3",
"NewlyAssignedL3",
"HoursLogged"
],
"dbCloning": [
"dva"
]
}
我已经映射了如下结构。
type receivers struct {
Gozo []string `json:"gozo"`
Dva []string `json:"dva"`
// Add more recievers
}
// Config -- The config object parsed from the JSON file
type Config struct {
ReportType string `json:"type"`
Clients []string `json:"clients"`
Sender string `json:"sender"`
Recipients receivers `json:"recipients"`
Cloning []string `json:"dbCloning"`
}
然后在另一个源文件的某处,我执行以下操作,
func main() {
conf := LoadConfig(os.Args[1])
for _, client := range conf.Clients {
// Use the client variable of some other function calls
fmt.Println(conf.Recipients[client]) // This will not work
}
现在我的问题是如何让它发挥作用。我无法直接遍历 conf.Recipients
。
PS:考虑 LoadConfig
函数解码 JSON 并返回一个 conf
对象。
编辑 1: 看起来像是设计决策错误。现在使用 map[string][]string
的解决方案。但不将其标记为答案,因为需要知道在没有其他选择的所有情况下如何轻松完成。
最佳答案
问题是您的类型 receivers
不应该有命名字段。它应该是 map[string][]string
。
这是一个工作示例:
package main
import (
"encoding/json"
"fmt"
)
type Config struct {
ReportType string `json:"type"`
Clients []string `json:"clients"`
Sender string `json:"sender"`
Recipients map[string][]string `json:"recipients"`
Cloning []string `json:"dbCloning"`
}
var data = []byte(`{
"type": "Weekly",
"clients": [
"gozo",
"dva"
],
"sender": "no-reply@flowace.in",
"recipients": {
"gozo": [
"a@gmail.com",
"b@hotmail.com"
],
"dva": [
"c@gmail.com",
"d@hotmail.com"
]
},
"features": [
"Top5UsedApps",
"TimeSpentOnEachL3",
"NewlyAssignedL3",
"HoursLogged"
],
"dbCloning": [
"dva"
]
}`)
func main() {
var conf Config
json.Unmarshal(data, &conf)
for _, client := range conf.Clients {
fmt.Println(conf.Recipients[client])
}
}
给出输出
[a@gmail.com b@hotmail.com]
[c@gmail.com d@hotmail.com]
关于json - 如何从字符串表示形式的变量中获取嵌套结构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51841131/