Parse yaml files with "---" in it

Viewed 516

I'm using https://github.com/go-yaml/yaml to parse yaml files:

type TestConfig struct {
   Test string `yaml:"test"`
}


yaml file:

test: 123

---

test: 456

But yaml.Unmarshal() only parses the first segment, how can I parse the rest of it?

1 Answers

But yaml.Unmarshal() only parses the first segment, how can I parse the rest of it?

yaml.Unmarshal's doc says (emphasis mine):

Unmarshal decodes the first document found within the in byte slice and assigns decoded values into the out value.

If you want to decode a series of documents, call yaml.NewDecoder() on a stream of your data and then call your decoder's .Decode(...) multiple times. Use io.EOF to identify the end of records.

I usually use an infinite for loop with a break condition for this:

decoder := yaml.NewDecoder(bytes.NewBufferString(data))
for {
    var d Doc
    if err := decoder.Decode(&d); err != nil {
        if err == io.EOF {
            break
        }
        panic(fmt.Errorf("Document decode failed: %w", err))
    }
    fmt.Printf("%+v\n", d)
}
fmt.Printf("All documents decoded")

(https://go.dev/play/p/01xdzDN0qB7)

Related