首页 > 解决方案 > 解析地图的 yaml 错误

问题描述

我有以下程序,我需要在其中使用以下结构解析 yaml

https://codebeautify.org/yaml-validator/cbabd352 这是有效的 yaml,我使用 byte 使其更简单,可能在复制粘贴到问题期间缩进已更改,但您可以在链接中看到 yaml 有效

yaml 有一个 api_version 和跑步者,对于每个跑步者(键是名字)我有一个命令列表,我需要打印这些命令function1function4我​​在这里做错了什么?

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

我无法更改 yaml,它应该完全像这样

https://codebeautify.org/yaml-validator/cbabd352

这是代码 https://play.golang.org/p/zidjOA6-gc7

标签: gostructyaml

解决方案


您提供的 yaml 包含令牌错误。在此处验证代码中使用的 yaml https://codebeautify.org/yaml-validator/cbaabb32

之后创建结构类型结果的变量而不是数组。因为您使用的 yaml 正在使用 Runners 数组和 api_version 创建一个结构。

这个

var runners []Result

应该

var runners Result

因为因为结构不是切片。获取 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
}

游乐场示例


推荐阅读