登录
首页 >  Golang >  Go问答

出现错误的Go语言中解析YAML

来源:stackoverflow

时间:2024-03-10 21:36:25 280浏览 收藏

对于一个Golang开发者来说,牢固扎实的基础是十分重要的,golang学习网就来带大家一点点的掌握基础知识点。今天本篇文章带大家了解《出现错误的Go语言中解析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 ,这里可能缺少什么?


解决方案


您发布的代码包含多个错误,包括结构字段 type。您的代码中提供的 yaml 无效。这将导致在将 yaml 解组到 struct 时出现错误。

在go中解组yaml时,需要:

解码值的类型应与 相应的值 in out。如果由于以下原因无法解码一个或多个值 对于类型不匹配,解码会部分继续,直到结束 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)
}

Playground example

在此处在线验证您的 yaml https://codebeautify.org/yaml-validator/cb92c85b

好了,本文到此结束,带大家了解了《出现错误的Go语言中解析YAML》,希望本文对你有所帮助!关注golang学习网公众号,给大家分享更多Golang知识!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>