Skip to content

Question: How can I parse multi yaml file? #664

Open
@wrbbz

Description

@wrbbz

Hello!
I've got a file with multiple yaml objects with the same structure. It looks like this:

---
apiVersion: ...
kind: ...
metadata:
  description: ...
spec:
  type: ...
---
apiVersion: ...
kind: ...
metadata:
  description: ...
spec:
  type: ...
---
. . .

I would like to parse each object separately and make some processing (i.e. validation)

I've tried the following approach ():

file, err := os.Open(yamlFile)
if err != nil {
  log.Fatal(err)
}

for {
  var yamlObject any
  dec := yaml.NewDecoder(file)
  if err := dec.Decode(&yamlObject); err != nil {
    log.Fatalf("Decoding error: %s", err)
  }

// some processing goes here

}

However, this parses only the first yaml block inside the file and the second iteration of for loop failes with EOF.

I've noticed this solution (somewhat like this) here. I understand, that this solution for another go-yaml, however, I would like to use this implementation

Also, I've noticed this issue which is also about multi-yaml file, so I've tried to initialize File type:

f, err := os.ReadFile(instanceFile)
if err != nil {
  log.Fatal(err)
}

var file ast.File
if _, err := file.Read(f); err != nil {
  log.Fatalln(err)
}

log.Println(len(file.Docs))

And all I've got is EOF

So, how can I properly parse multi-yaml file?

Metadata

Metadata

Assignees

No one assigned

    Labels

    questionFurther information is requested

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions