Go:解析多变的YAML

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

Go: parsing variative YAML

问题

我可以帮你翻译这段内容。以下是翻译的结果:

我想要在Go语言中使用yaml.v2库来解析包含不同值的映射(map),该如何操作?

目前,我有以下节点描述:

package executors

type OptionMap map[string][]string

type Step struct {
    Exec string
    Pwd  string
    Opts OptionMap
}

示例的YAML如下:

steps:
   - exec: maven
     pwd: /code
     opts:
       goals:
         - clean
         - install
       mvn_home: /maven

显然,只有当goals存在而mvn_home不存在时,节点才会被解析。有没有办法为这样的节点编写单一的描述?

如果没有,有没有办法将YAML的某个部分(在某个键下)作为普通字符串或者更好的方式,将其作为map[string]OBJECT类型的映射,并将该OBJECT单独解析?

英文:

I want to unmarshall map, which can contain different values, how can I do it in Go with yaml.v2?

Currently, I have the following node description:

package executors

type OptionMap map[string][]string

type Step struct {
    Exec string
 	Pwd  string
    Opts OptionMap
}

Sample YAML is the following:

steps:
   - exec: maven
     pwd: /code
     opts:
       goals:
         - clean
         - install
       mvn_home: /maven

Obviously, node will be unmarshaled if only goals, but not mvn_home will present there. Is there any way to write the single description for such node?

If no, is there any way to read some part of YAML (under some key) as a plain string or, better, such sort of map as map[string]OBJECT and unmarshal that OBJECT separately?

答案1

得分: 0

尝试使用map[string]interface{}进行解组。使用interface{}可以在需要时稍后解组。

英文:

Try using map[string]interface{} to unmarshal. With interface{} you can unmarshal it later when required.

huangapple
  • 本文由 发表于 2015年11月29日 19:33:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/33982311.html
匿名

发表评论

匿名网友

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

确定