英文:
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"`
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论