如何解析动态键

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

How unmarshal dynamic keys

问题

我有一个具有以下结构的yaml文件:

mappings:
  extgroup1:
  - somescope1
  - somescope2

  someextgroup:
  - somescope3

  allusers:
  - somescope1

这些映射基本上是一个数组,但结构只是一组动态的键。我想将其解组成一个新数据类型的数组,如下所示:

type ExternalGroupMapping struct {
	ExternalGroup string
	Scopes        []string
}

所以,它看起来会像这样:

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

类似于jq中的to_entries

这种操作是否可行?甚至不确定从哪里开始。

谢谢!

英文:

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!

答案1

得分: 0

没有自定义的封送,您可以通过将动态键映射到映射键来实现此目的。每个映射似乎是一个作用域数组,因此可以这样做:

type Mappings struct {
   Mappings map[string][]string `yaml:"mappings"`
}
英文:

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"`
}

huangapple
  • 本文由 发表于 2021年10月2日 00:27:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/69409189.html
匿名

发表评论

匿名网友

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

确定