我正在尝试读取包含对象数组的 yaml 文件
package config import ( "gopkg.in/yaml.v3" "log" "os" "path/filepath" "runtime" ) type documentationinfo struct { docs []document `yaml:"document"` } type document struct { title string `yaml:"title"` filename string `yaml:"filename"` } func (c *documentationinfo) init() map[string]document { _, b, _, _ := runtime.caller(0) basepath := filepath.dir(b) yamlfile, err := os.readfile(basepath + "/documentation.yaml") if err != nil { log.printf("yamlfile.get err #%v ", err) } err = yaml.unmarshal(yamlfile, c.docs) if err != nil { log.fatalf("unmarshal: %v", err) } docinfo := make(map[string]document) for _, doc := range c.docs { docinfo[doc.filename] = doc } return docinfo } func newdocumentconfig() *documentationinfo { return &documentationinfo{} }
yaml 文件
documentationinfo: document: - {filename: "foo.md", title: "i am an foo title"} - {filename: "test.md", title: "i am an test title"} - {filename: "bar.md", title: "i am an bar title"} - {filename: "nice.md", title: "i am an nice title"}
错误
2023/06/27 13:44:44 Unmarshal: yaml: unmarshal errors: line 1: cannot unmarshal !!map into []config.Document
我不确定问题是否是 yaml 文件语法,因为它与 json 类似,但交叉引用文档看起来是正确的。
如有任何建议,我们将不胜感激...
您已将最外层容器定义为带有 document
键的映射,其中包含 document
s 数组:
type documentationinfo struct { docs []document `yaml:"document"` }
但这不是输入数据的结构,它看起来像这样:
documentationinfo: document: - {filename: "foo.md", title: "i am an foo title"} - {filename: "test.md", title: "i am an test title"} - {filename: "bar.md", title: "i am an bar title"} - {filename: "nice.md", title: "i am an nice title"}
外部元素是一个包含 documentationinfo
键的映射(该键的值是带有 document
键的映射)。您需要像这样重新定义您的类型(我已将其转换为 package main
,以便我可以在本地运行它进行测试):
package main import ( "fmt" "log" "os" "path/filepath" "runtime" "gopkg.in/yaml.v3" ) type documentationinfofile struct { documentationinfo documentationinfo `yaml:"documentationinfo"` } type documentationinfo struct { docs []document `yaml:"document"` } type document struct { title string `yaml:"title"` filename string `yaml:"filename"` } func (docinfo *documentationinfofile) init() map[string]document { _, b, _, _ := runtime.caller(0) basepath := filepath.dir(b) yamlfile, err := os.readfile(basepath + "/documentation.yaml") if err != nil { log.printf("yamlfile.get err #%v ", err) } err = yaml.unmarshal(yamlfile, docinfo) if err != nil { log.fatalf("unmarshal: %v", err) } docmap := make(map[string]document) for _, doc := range docinfo.documentationinfo.docs { docmap[doc.filename] = doc } return docmap } func newdocumentconfig() *documentationinfofile { return &documentationinfofile{} } func main() { d := newdocumentconfig() docmap := d.init() fmt.printf("%+vn", docmap) }
运行上面的代码会产生:
65bcd85880费用