解析带有”—“的yaml文件。

huangapple go评论83阅读模式
英文:

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")

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

huangapple
  • 本文由 发表于 2022年1月31日 09:07:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/70920334.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定