YAML 解组映射[字符串]结构

use*_*173 7 yaml go

我绝对不明白这一点。这是给定的 yaml 文件

items:
  - item1:
      one: "some"
      two: "some string"
  - item2:
      one: "some"
      two: "some string"
Run Code Online (Sandbox Code Playgroud)

和一个配置:

items:
  - item1:
      one: "some"
      two: "some string"
  - item2:
      one: "some"
      two: "some string"
Run Code Online (Sandbox Code Playgroud)

我在用gopkg.in/yaml.v2

出现此错误:

Unmarshal: yaml: unmarshal errors:
  line 6: cannot unmarshal !!seq into map[string]application.Item
Run Code Online (Sandbox Code Playgroud)

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

Bur*_*dar 6

您的映射存在多个问题:

  • Item结构成员不被导出。你必须导出它们:
type Item struct {
    One string `yaml:"one"`
    Two string `yaml:"two"`
}
Run Code Online (Sandbox Code Playgroud)
  • ItemsItem是s的映射数组
type conf struct {
    Items []map[string]Item `yaml:"items"`
}
Run Code Online (Sandbox Code Playgroud)


Ole*_*leg 6

首先,您需要将 YAML 更改为

  items:
      item1:
        one: "some"
        two: "some string"
      item2:
        one: "some"
        two: "some string"
Run Code Online (Sandbox Code Playgroud)

然后,在你的 go 代码中

type Config struct {
    Items map[string]Item
}

type Item struct {
    One string
    Two string
}
Run Code Online (Sandbox Code Playgroud)

然后与

fmt.Printf("%+v\n", c.Items)
Run Code Online (Sandbox Code Playgroud)

你将会拥有

map[item1:{One:some Two:some string} item2:{One:some Two:some string}]
Run Code Online (Sandbox Code Playgroud)