go - YAML Unmarshal map [string] struct

标签 go yaml

我绝对不明白这一点。这是给定的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

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

最佳答案

首先,您需要将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}]

关于go - YAML Unmarshal map [string] struct,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61943470/

相关文章:

已有字节缓冲区 slice 时的 Golang Reader 接口(interface)实现

yaml - 无服务器框架试运行或测试,无需部署

amazon-web-services - 用户 : batch. amazonaws.com 无权对资源执行:sts:AssumeRole

r - 在 Rmarkdown 文档的 YAML-Header 部分包含额外的文本/超链接部分

php - 重定向不适用于 Cloud SQL

go - 一个项目中有多个软件包?

interface - 努力了解接口(interface)类型的用途

go - 在golang中查找和删除 slice 中的元素

Go slice 存储在动态内存或静态内存中

php - 是否可以创建一个指向绝对外部 URL 的路由?