如何直接访问YAML unmarshall中的嵌套内部键值对?

huangapple go评论103阅读模式
英文:

How to access nested inner key-values directly in YAML unmarshall

问题

我的配置文件包含多个内部结构的结构化配置,这里是一个公司的例子。

在顶层,我想直接访问我在config.yaml中已知存在的公司的特定属性。

是否可以只使用结构标签来进行解组操作?

  1. package main
  2. import (
  3. "fmt"
  4. "gopkg.in/yaml.v2"
  5. )
  6. type Org struct {
  7. Ceo string `yaml:"ceo"`
  8. }
  9. type Config struct {
  10. Companies map[string]Org `yaml:"companies"`
  11. GoogleCEO string `yaml:"companies.google.ceo"`
  12. }
  13. func main() {
  14. var config Config
  15. yamlFile := []byte(`companies:
  16. google:
  17. ceo: "Sundar Pichai"
  18. amazon:
  19. ceo: "Jeff Bezos"`)
  20. err := yaml.Unmarshal(yamlFile, &config)
  21. check(err)
  22. fmt.Printf("config:\n%#v", config)
  23. }
  24. func check(e error) {
  25. if e != nil {
  26. panic(e)
  27. }
  28. }

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?

  1. package main
  2. import (
  3. "fmt"
  4. "gopkg.in/yaml.v2"
  5. )
  6. type Org struct {
  7. Ceo string `yaml:"ceo"`
  8. }
  9. type Config struct {
  10. Companies map[string]Org `yaml:"companies"`
  11. GoogleCEO string `yaml:"companies.google.ceo"`
  12. }
  13. func main() {
  14. var config Config
  15. yamlFile := []byte(`companies:
  16. google:
  17. ceo: "Sundar Pichai"
  18. amazon:
  19. ceo: "Jeff Bezos"`)
  20. err := yaml.Unmarshal(yamlFile, &config)
  21. check(err)
  22. fmt.Printf("config:\n%#v", config)
  23. }
  24. func check(e error) {
  25. if e != nil {
  26. panic(e)
  27. }
  28. }

https://go.dev/play/p/G_1NV46yWrv

答案1

得分: 1

很抱歉,你不能使用标签来实现这个。最接近的选项是嵌套结构体:

  1. type Config struct {
  2. Companies struct {
  3. Google struct {
  4. CEO string `yaml:"ceo"`
  5. } `yaml:"google"`
  6. } `yaml:"companies"`
  7. }

https://go.dev/play/p/28pcPUiZvO-

英文:

Unfortunately, you cannot do it with tags.

Closest option is nested structs:

  1. type Config struct {
  2. Companies struct {
  3. Google struct {
  4. CEO string `yaml:"ceo"`
  5. } `yaml:"google"`
  6. } `yaml:"companies"`
  7. }

https://go.dev/play/p/28pcPUiZvO-

huangapple
  • 本文由 发表于 2022年6月2日 05:32:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/72468290.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定