我有以下程序,其中我需要使用以下结构来解析yaml:
https://codebeautify.org/yaml- validator/cbabd352 这是 有效的Yaml ,我使用字节使其更简单,也许缩进在复制粘贴到问题的过程中已更改,但您可以在链接中看到yaml有效
YAML的有API_VERSION和亚军,每个转轮(关键是名字),我已经命令的列表,我需要打印这些命令function1和function4,我究竟错在这里做什么?
function1
function4
package main import ( "fmt" "log" "gopkg.in/yaml.v2" ) var runContent = []byte(` api_ver: 1 runners: - name: function1 type: - command: spawn child process - command: build - command: gulp - name: function2 type: - command: run function 1 - name: function3 type: - command: ruby build - name: function4 type: - command: go build `) type Result struct { Version string `yaml:"api_ver"` Runners []Runners `yaml:"runners"` } type Runners struct { Name string `yaml:"name"` Type []Command `yaml:"type"` } type Command struct { Command string `yaml:"command"` } func main() { var runners []Result err := yaml.Unmarshal(runContent, &runners) if err != nil { log.Fatalf("Error : %v", err) } fmt.Printf("%+v", runners[0]) }
我得到的错误 cannot unmarshal !!map into []main.Result
cannot unmarshal !!map into []main.Result
我无法更改Yaml,应该完全像这样
https://codebeautify.org/yaml- validator/cbabd352
这是代码 https://play.golang.org/p/zidjOA6-gc7
您提供的Yaml令牌中包含错误。在此处验证代码中使用的Yaml https://codebeautify.org/yaml- validator/cbaabb32
之后,创建结构类型的变量结果而不是数组。因为您使用的Yaml正在使用Runners数组和api_version创建一个结构。
这个
var runners []Result
应该
var runners Result
因为因为struct不是切片。为yaml中使用的功能名称获取命令列表。您需要遍历runners数组以查找函数名称并获取该函数的命令值。下面是工作代码:
package main import ( "fmt" "log" "gopkg.in/yaml.v2" ) var runContent = []byte(` api_ver: 1 runners: - name: function1 type: - command: spawn child process - command: build - command: gulp - name: function2 type: - command: run function 1 - name: function3 type: - command: ruby build - name: function4 type: - command: go build `) type Result struct { Version string `yaml:"api_ver"` Runners []Runners `yaml:"runners"` } type Runners struct { Name string `yaml:"name"` Type []Command `yaml:"type"` } type Command struct { Command string `yaml:"command"` } func main() { var runners Result // parse mta yaml err := yaml.Unmarshal(runContent, &runners) if err != nil { log.Fatalf("Error : %v", err) } commandList := getCommandList("function1", runners.Runners) fmt.Printf("%+v", commandList) } func getCommandList(name string, runners []Runners) []Command { var commandList []Command for _, value := range runners { if value.Name == name { commandList = value.Type } } return commandList }
操场上的例子