go - 如何将 yaml 解析/解组为数据结构
问题描述
我有以下 yaml,我想将其解析为 Go
env:
production:
asia:
blue: config.prod-asia
ph:
blue: prod.ph.config.blue
green: prod.phconfig.green
staging:
asia:
blue: asia.config.blue
ph:
blue: phconfig.blue
green: ph.config.green
但是我尝试了以下结构不起作用。
type env struct {
Env map[string]region `yaml:"env"`
}
type region struct {
Region map[string]config
}
type config map[string]string
我应该如何构建我的结构,以便我可以解析成如下的数据结构?
func main() {
var d env
source, err := ioutil.ReadFile("config.yaml")
if err != nil {
log.Fatal("Couldn't read yaml file.")
}
err = yaml.Unmarshal(source, &d)
if err != nil {
log.Fatal("Couldn't parse yaml file.")
}
fmt.Println(d)
}
上面运行时的输出是
# go run .
{map[production:{map[]} staging:{map[]}]}
使用的 yaml 库"gopkg.in/yaml.v2"
解决方案
type env struct {
Env map[string]map[string]map[string]string `yaml:"env"`
}
用上面的例子解决了
推荐阅读
- dask - Dask 如何处理函数定义中的外部或全局变量?
- javascript - 如何使用 JQuery 根据 Ids 搜索 JSON 对象
- apache-kafka - whatsapp 或 FB Messenger 中使用的队列
- powershell - Powershell3.0 导出csv追加
- oracle - 变量定义为引用表的列类型,但未在 oracle pl sql 中计算或初始化
- android - 以编程方式设置 Always-On VPN,“管理员不拥有配置文件”
- angular - TypeError:无法读取未定义的属性“defaultView” - Angular
- python - 用于 openpyxl 多个图表创建的 for 循环
- c# - 如何改进这个有效的 sql 依赖实现?
- php - 如何处理 Zapier 中的错误?