Home > Back-end >  How unmarshal dynamic keys
How unmarshal dynamic keys

Time:10-04

I have a yaml file with the follow structure:

mappings:
  extgroup1:
  - somescope1
  - somescope2

  someextgroup:
  - somescope3

  allusers:
  - somescope1

The mappings are basically an array, but the structure is just a dynamic set of keys. I want to unmarshall this into an array of a new data type like so:

type ExternalGroupMapping struct {
    ExternalGroup string
    Scopes        []string
}

So, it would look something like:

[]Mappings{
     ExternalGroupMapping{
         ExternalGroup: "extgroup1"
         Scopes: []string{"somescope1", "somescope2"}
     },
     ExternalGroupMapping{
         ExternalGroup: "someextgroup"
         Scopes: []string{"somescope3"}
     },
     ExternalGroupMapping{
         ExternalGroup: "allusers"
         Scopes: []string{"somescope1"}
     }
}

Similar to something like to_entries in jq

Is something like this possible? Not even sure where to begin.

Thanks!

CodePudding user response:

Without custom marshaling, you can do this by mapping dynamic keys to map keys. Each mapping appear to be an array of scopes, so:

type Mappings struct {
   Mappings map[string][]string `yaml:"mappings"`
}
  • Related