英文:
Parse yaml files with "---" in it
问题
我正在使用https://github.com/go-yaml/yaml来解析yaml文件:
type TestConfig struct {
   Test string `yaml:"test"`
}
yaml文件内容如下:
test: 123
---
test: 456
但是yaml.Unmarshal()只解析了第一个部分,我该如何解析剩余的部分呢?
英文:
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
得分: 4
yaml.Unmarshal()只解析第一个片段,那么我如何解析其余部分呢?
yaml.Unmarshal的文档中提到(重点在于):
Unmarshal解码输入字节切片中找到的第一个文档,并将解码后的值赋给输出值。
如果你想解码一系列的文档,请在数据流上调用yaml.NewDecoder(),然后多次调用解码器的.Decode(...)方法。使用io.EOF来标识记录的结束。
通常我会使用一个无限的for循环,并设置一个break条件:
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)
英文:
> 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")
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论