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

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

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)
	}
}

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

答案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"`
}

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:

确定