在 golang 中解析 yaml 时出错

我有一个像下面这样的 yaml,我需要使用 go 来解析它。当我尝试使用解析运行代码时出现错误。下面是代码:


var runContent= []byte(`


- runners:

   - name: function1

     type: func1

      - command: spawn child process

      - command: build

      - command: gulp


  - name: function1

    type: func2

      - command: run function 1

  - name: function3

    type: func3

      - command: ruby build


  - name: function4

    type: func4

      - command: go build 


`)

这些是类型:


type Runners struct {


    runners string `yaml:"runners"`

        name string `yaml:”name”`

        Type: string  `yaml: ”type”`

        command  [] Command 

}



type Command struct {

    command string `yaml: ”command”`

}




runners := Runners{}

err = yaml.Unmarshal(runContent, &runners)

if err != nil {

    log.Fatalf("Error : %v", err)

}

当我尝试解析它时出现错误invalid map,这里可能遗漏了什么?


跃然一笑
浏览 241回答 1
1回答

烙印99

您发布的代码包含多个错误,包括 struct field Type。您的代码中提供的 yaml 无效。这将导致在将 yaml 解组为结构时出错。在 go 中解组 yaml 时,要求:解码值的类型应与输出中的相应值兼容。如果一个或多个值由于类型不匹配而无法解码,解码将继续部分进行,直到 YAML 内容结束,并返回一个 *yaml.TypeError,其中包含所有缺失值的详细信息。与此同时:结构字段只有在导出时才会被解组(首字母大写),并且使用小写的字段名称作为默认键进行解组。定义标签时也有错误yaml,其中包含空格。自定义键可以通过字段标签中的“yaml”名称来定义:第一个逗号之前的内容用作键。type Runners struct {    runners string `yaml:"runners"` // fields should be exportable        name string `yaml:”name”`        Type: string  `yaml: ”type”` // tags name should not have space in them.        command  [] Command } 要使结构可导出,请将结构和字段转换为大写首字母并删除 yaml 标签名称中的空格:type Runners struct {    Runners string `yaml:"runners"`    Name string `yaml:"name"`    Type string `yaml:"type"`    Command  []Command }type Command struct {    Command string `yaml:"command"`}修改下面的代码以使其工作。package mainimport (    "fmt"    "log"    "gopkg.in/yaml.v2")var runContent = []byte(`- runners:  - name: function1    type:    - command: spawn child process    - command: build    - command: gulp  - name: function1    type:    - command: run function 1  - name: function3    type:    - command: ruby build  - name: function4    type:    - command: go build`)type Runners []struct {    Runners []struct {        Type []struct {            Command string `yaml:"command"`        } `yaml:"type"`        Name string `yaml:"name"`    } `yaml:"runners"`}func main() {    runners := Runners{}    // parse mta yaml    err := yaml.Unmarshal(runContent, &runners)    if err != nil {        log.Fatalf("Error : %v", err)    }    fmt.Println(runners)}游乐场示例在此处在线验证您的 yaml https://codebeautify.org/yaml-validator/cb92c85b
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go