英文:
How to access nested inner key-values directly in YAML unmarshall
问题
我的配置文件包含多个内部结构的结构化配置,这里是一个公司的例子。
在顶层,我想直接访问我在config.yaml中已知存在的公司的特定属性。
是否可以只使用结构标签来进行解组操作?
package main
import (
"fmt"
"gopkg.in/yaml.v2"
)
type Org struct {
Ceo string `yaml:"ceo"`
}
type Config struct {
Companies map[string]Org `yaml:"companies"`
GoogleCEO string `yaml:"companies.google.ceo"`
}
func main() {
var config Config
yamlFile := []byte(`companies:
google:
ceo: "Sundar Pichai"
amazon:
ceo: "Jeff Bezos"`)
err := yaml.Unmarshal(yamlFile, &config)
check(err)
fmt.Printf("config:\n%#v", config)
}
func check(e error) {
if e != nil {
panic(e)
}
}
https://go.dev/play/p/G_1NV46yWrv
英文:
My configs contain multiple structured configs of an inner struct, in this case- a company.
At the top-level, I want access directly to a particular attribute in a company I know exists in my config.yaml.
Is it possible to have this unmarshalling using just struct tags?
package main
import (
"fmt"
"gopkg.in/yaml.v2"
)
type Org struct {
Ceo string `yaml:"ceo"`
}
type Config struct {
Companies map[string]Org `yaml:"companies"`
GoogleCEO string `yaml:"companies.google.ceo"`
}
func main() {
var config Config
yamlFile := []byte(`companies:
google:
ceo: "Sundar Pichai"
amazon:
ceo: "Jeff Bezos"`)
err := yaml.Unmarshal(yamlFile, &config)
check(err)
fmt.Printf("config:\n%#v", config)
}
func check(e error) {
if e != nil {
panic(e)
}
}
答案1
得分: 1
很抱歉,你不能使用标签来实现这个。最接近的选项是嵌套结构体:
type Config struct {
Companies struct {
Google struct {
CEO string `yaml:"ceo"`
} `yaml:"google"`
} `yaml:"companies"`
}
https://go.dev/play/p/28pcPUiZvO-
英文:
Unfortunately, you cannot do it with tags.
Closest option is nested structs:
type Config struct {
Companies struct {
Google struct {
CEO string `yaml:"ceo"`
} `yaml:"google"`
} `yaml:"companies"`
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论