你在学习Golang相关的知识吗?本文《如何从字符串表示形式的变量中获取嵌套结构?》,主要介绍的内容就涉及到,如果你想提升自己的开发能力,就不要错过这篇文章,大家要知道编程理论基础和实战操作都是不可或缺的哦!
我有一个 json 文件,看起来像下面这样
{
"type": "weekly",
"clients": [
"gozo",
"dva"
],
"sender": "[email protected]",
"recipients": {
"gozo": [
"[email protected]",
"[email protected]"
],
"dva": [
"[email protected]",
"[email protected]"
]
},
"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": "[email protected]",
"recipients": {
"gozo": [
"[email protected]",
"[email protected]"
],
"dva": [
"[email protected]",
"[email protected]"
]
},
"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])
}
}
给出输出
[[email protected] [email protected]] [[email protected] [email protected]]
今天关于《如何从字符串表示形式的变量中获取嵌套结构?》的内容介绍就到此结束,如果有什么疑问或者建议,可以在golang学习网公众号下多多回复交流;文中若有不正之处,也希望回复留言以告知!
本文内容来源于互联网,如有侵权请联系删除。
