解析 YAML 而不知道字段名称

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

Parse YAML without knowing field names

问题

我正在尝试解析一个具有以下结构的YAML文件:

contacts:
  teamone:
    email:
      to: 'email.one@email.com'

我可以像这样获取电子邮件地址:

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

我的问题是,如何从一个像这样的YAML文件中获取所有的电子邮件地址(或特定的地址):

contacts:
  teamone:
    email:
      to: 'email.one@email.com'
  teamtwo:
    email:
      to: 'email.two@email.com'

此外,人们可以随时向该文件中添加新的团队/电子邮件地址。

这个目的是从一个YAML文件中查找联系人详细信息。所以有人可以运行程序,提供一个团队(例如"teamnine"),输出将是与该条目相关联的电子邮件。

任何建议都将不胜感激。

英文:

I am trying to parse a YAML file which has the following structure:

contacts:
  teamone:
    email:
      to: 'email.one@email.com'

I am able to get email address out like this:

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

My question is, how can I get out all the email addresses (or a specific address) from a YAML file that looks like this:

contacts:
  teamone:
    email:
      to: 'email.one@email.com'
  teamtwo:
    email:
      to: 'email.two@email.com'

Also, people could be adding new teams/email addresses to this file at any time.

The purpose of this comes from looking up contact details from a YAML file. So someone could run the program, provide it with a team (for example "teamnine") and the output would be the email associated with that entry.

Any advice would be appreciated.

答案1

得分: 1

Team定义为一个单独的结构体,并使用map:

type Team struct {
   Email struct {
      To string `yaml:"to"`
   } `yaml:"email"`
}

type Contacts struct {
   Contacts map[string]Team `yaml:"contacts"`
}
英文:

Define Team as a separate struct, and use a map:

type Team struct {
   Email struct {
	  To string `yaml:"to"`
   } `yaml:"email"`
}

type Contacts struct {
	Contacts  map[string]Team `yaml:"contacts"`
}

huangapple
  • 本文由 发表于 2021年11月23日 11:13:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/70074969.html
匿名

发表评论

匿名网友

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

确定