3 回答

TA貢獻1911條經驗 獲得超7個贊
gopkg.in/yaml.v2 和 gopkg.in/yaml.v3 之間的行為有所不同:
V2:https://play.golang.org/p/XScWhdPHukO V3: https: //play.golang.org/p/OfFY4qH5wW2
恕我直言,這兩種實現都會產生不正確的結果,但 V3 顯然稍差一些。
有一個解決方法。如果您稍微更改接受的答案中的代碼,它可以正常工作,并且與兩個版本的 yaml 包以相同的方式工作:https://play.golang.org/p/r4ogBVcRLCb

TA貢獻1808條經驗 獲得超4個贊
Currentgopkg.in/yaml.v3 Deocder產生非常正確的結果,您只需要注意為每個文檔創(chuàng)建新結構并檢查它是否被正確解析(使用nil檢查),并EOF正確處理錯誤:
package main
import "fmt"
import "gopkg.in/yaml.v3"
import "os"
import "errors"
import "io"
type Spec struct {
Name string `yaml:"name"`
}
func main() {
f, err := os.Open("spec.yaml")
if err != nil {
panic(err)
}
d := yaml.NewDecoder(f)
for {
// create new spec here
spec := new(Spec)
// pass a reference to spec reference
err := d.Decode(&spec)
// check it was parsed
if spec == nil {
continue
}
// break the loop in case of EOF
if errors.Is(err, io.EOF) {
break
}
if err != nil {
panic(err)
}
fmt.Printf("name is '%s'\n", spec.Name)
}
}
測試文件spec.yaml:
---
name: "doc first"
---
name: "second"
---
---
name: "skip 3, now 4"
---

TA貢獻1893條經驗 獲得超10個贊
我發(fā)現使用的解決方案gopkg.in/yaml.v2:
package main
import (
"bytes"
"fmt"
"io/ioutil"
"log"
"path/filepath"
"gopkg.in/yaml.v2"
)
type T struct {
A string
B struct {
RenamedC int `yaml:"c"`
D []int `yaml:",flow"`
}
}
func main() {
filename, _ := filepath.Abs("./example.yaml")
yamlFile, err := ioutil.ReadFile(filename)
if err != nil {
panic(err)
}
r := bytes.NewReader(yamlFile)
dec := yaml.NewDecoder(r)
var t T
for dec.Decode(&t) == nil {
fmt.Printf("a :%v\nb :%v\n", t.A, t.B)
}
}
- 3 回答
- 0 關注
- 206 瀏覽
添加回答
舉報