Home > Enterprise >  Parse YAML without knowing field names
Parse YAML without knowing field names

Time:11-24

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

contacts:
  teamone:
    email:
      to: '[email protected]'

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 protected]'
  teamtwo:
    email:
      to: '[email protected]'

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.

CodePudding user response:

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"`
}
  •  Tags:  
  • go
  • Related