YAML Unmarshal map[string]struct

我绝对没有得到这个。这是给定的 yaml 文件


items:

  - item1:

      one: "some"

      two: "some string"

  - item2:

      one: "some"

      two: "some string"

和一个配置:


type Item struct {

    one string

    two string

}

type conf struct {

    Items map[string]Item

}


func (c *conf) getConfig(filename string) *conf {


    yamlFile, err := ioutil.ReadFile(filename)

    if err != nil {

        log.Printf("yamlFile.Get err   #%v ", err)

    }

    err = yaml.Unmarshal(yamlFile, &c)

    if err != nil {

        log.Fatalf("Unmarshal: %v", err)

    }


    //c.Items = make(map[string]Items)

    return c

}

我在用gopkg.in/yaml.v2


出现此错误:


Unmarshal: yaml: unmarshal errors:

  line 6: cannot unmarshal !!seq into map[string]application.Item

请帮助我理解我在这里做错了什么。我已经到处搜索了。提前致谢。


POPMUISE
浏览 1093回答 3
3回答

哈士奇WWW

首先,您需要将 YAML 更改为  items:      item1:        one: "some"        two: "some string"      item2:        one: "some"        two: "some string"然后,在你的代码中type Config struct {    Items map[string]Item}type Item struct {    One string    Two string}然后与fmt.Printf("%+v\n", c.Items)你将会有map[item1:{One:some Two:some string} item2:{One:some Two:some string}]

qq_花开花谢_0

您的映射存在多个问题:Item不导出结构成员。您必须导出它们:type Item struct {    One string `yaml:"one"`    Two string `yaml:"two"`}Items是Items的映射数组type conf struct {    Items []map[string]Item `yaml:"items"`}

慕盖茨4494581

我的场合是,我将 yaml 定义如下:idl:  protobuf:    executable: protoc    version_min: v3.6.0    version_cmd: "protoc --version | awk '{ print $2 }'"    install_cmd: ""    fallback: "please install protoc first, see: https://github.com/protocolbuffers/protobuf"  flatbuffers:    executable: flatc    version_min: 2.0.0    version_cmd: "flatc --version | awk '{ print $3 }'"    install_cmd: ""    fallback: "please install flatc first, see: https://google.github.io/flatbuffers/flatbuffers_guide_building.html"我想将yaml转换为Config类型,定义为:type Dependency struct {    Executable string `yaml:"executable"`      VersionMin string `yaml:"version_min"`     VersionCmd string `yaml:"version_cmd"`     InstallCmd string `yaml:"install_cmd"`     Fallback   string `yaml:"fallback"`    }type Config struct {    IDL       map[string]*Dependency          `yaml:"idl"`    ...}它报告一个错误:yaml: unmarshal errors: line 5: cannot unmarshal !!seq into map[string]*config.Dependency。我搜索了相关问题和yaml教程,我认为我的yaml文件是可以的。我真的很困惑。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go