Home > Software engineering >  Go Yaml parse when file starts with -
Go Yaml parse when file starts with -

Time:01-01

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.

CodePudding user response:

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.

  • Related