Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Parse yaml files with "—" in it

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading