当文件以“-”开头时,使用Go Yaml解析。

huangapple go评论100阅读模式
英文:

Go Yaml parse when file starts with -

问题

我正在尝试使用"gopkg.in/yaml.v3"包将一个yaml文件解析为go语言。我还没有解决的问题是解析以"-"开头的文件。例如:

---
- type: people
  info:
   - { name: John, last: Doe }
   ...

所以当我尝试解析这个文件时:

package main

import (
  "fmt"
  "io/ioutil"
  "log"
  
  "gopkg.in/yaml.v3"
)

type YamlFile struct {
  Type string `yaml:"type"`
}

func main() {
        d := YamlFile{}

        src, err := ioutil.ReadFile("test1.yaml")
        if err != nil {
                log.Println(err)
        }

        err = yaml.Unmarshal(src, &d)
        if err != nil {
                log.Printf("error: %v", err)
        }

        fmt.Println(d)
}

输出:error: yaml: unmarshal errors: line 2: cannot unmarshal !!seq into main.YamlFile

当文件中的"-"被移除时,上述代码可以正常工作:

---
type: people
info:
   - { name: John, last: Doe }
...

然而,我无法重新格式化文件,所以我需要知道在尝试保留"-"的情况下我做错了什么。感谢任何指导。

英文:

I am trying to parse a yaml file into go using the "gopkg.in/yaml.v3" package.
The problem I haven't been able to solve is parsing a file starting with a -. For example:

---
- type: people
  info:
   - { name: John, last: Doe }
   ...

So when I try to parse this

package main

import (
  "fmt"
  "io/ioutil"
  "log"
  
  "gopkg.in/yaml.v3"
)

type YamlFile struct {
  type string `yaml:"type"`
}

func main() {
        d := YamlFile{}

        src, err := ioutil.ReadFile("test1.yaml")
        if err != nil {
                log.Println(err)
        }

        err = yaml.Unmarshal(src, &d)
        if err != nil {
                log.Printf("error: %v", err)
        }

        fmt.Println(d)
}

output: error: yaml: unmarshal errors:
line 2: cannot unmarshal !!seq into main.YamlFile

The above code works when the - is removed from the file

---
type: people
info:
   - { name: John, last: Doe }
...

However I cannot reformat the file so I need to know what I am doing wrong trying to parse with the - in place. Thanks for any pointers in the right direction.

答案1

得分: 2

- 表示这是一个列表/数组。因此,在Go中,你必须将其解组为切片或数组。

d := YamlFile{} 改为 d := []YamlFile{},你就不会再收到那个错误了。

但请注意,你使用的结构体始终会得到一个空结果,因为它没有导出的字段。

可以尝试使用以下代码:

type YamlFile struct {
  Type string `yaml:"type"`
}

在 playground 上查看示例

英文:

The - indicates that it's a list/array. Therefore you must unmarshal into a slice or array in Go.

Change d := YamlFile{} to d := []YamlFile{}, and you will no longer get that error.

But also note that you'll always get an empty result with the struct you've defined, because it has no exported fields.

Try instead:

type YamlFile struct {
  Type string `yaml:"type"`
}

See it on the playground.

huangapple
  • 本文由 发表于 2022年1月1日 00:00:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/70543891.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定