为了账号安全,请及时绑定邮箱和手机立即绑定

在 golang 中解析 yaml 时出错

在 golang 中解析 yaml 时出错

Go
跃然一笑 2023-03-21 15:19:28
我有一个像下面这样的 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,这里可能遗漏了什么?
查看完整描述

1 回答

?
烙印99

TA贡献1829条经验 获得超13个赞

您发布的代码包含多个错误,包括 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 main


import (

    "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


查看完整回答
反对 回复 2023-03-21
  • 1 回答
  • 0 关注
  • 240 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号