【问题标题】:Go Unmarshal YAML into struct with maps使用地图将 YAML 解组到结构中
【发布时间】:2016-08-27 02:47:48
【问题描述】:

我正在尝试将 YAML 文件解组为包含两个映射的结构(使用 go-yaml)。

YAML 文件:

'Include':
    - 'string1'
    - 'string2'

'Exclude':
    - 'string3'
    - 'string4'

结构:

type Paths struct {
    Include map[string]struct{}
    Exclude map[string]struct{}
}

尝试解组的函数的简化版本(即删除错误处理等):

import "gopkg.in/yaml.v2"

func getYamlPaths(filename string) (Paths, error) {
    loadedPaths := Paths{
        Include: make(map[string]struct{}),
        Exclude: make(map[string]struct{}),
    }

    filenameabs, _ := filepath.Abs(filename)
    yamlFile, err := ioutil.ReadFile(filenameabs)

    err = yaml.Unmarshal(yamlFile, &loadedPaths)
    return loadedPaths, nil
}

正在从文件中读取数据,但解组函数没有将任何内容放入结构中,并且没有返回错误。

我怀疑 unmarshal-function 无法将 YAML 集合转换为 map[string]struct{},但如前所述,它不会产生任何错误,我环顾四周寻找类似的问题,但似乎找不到任何错误。

任何线索或见解将不胜感激!

【问题讨论】:

    标签: go yaml


    【解决方案1】:

    通过调试发现了多个问题。首先,yaml 似乎并不关心字段名称。您必须使用

    注释字段
    `yaml:"NAME"`
    

    其次,在 YAML 文件中,IncludeExclude 都只包含一个字符串列表,而不是类似于地图的东西。所以你的结构变成了:

    type Paths struct {
        Include []string `yaml:"Include"`
        Exclude []string `yaml:"Exclude"`
    }
    

    而且它有效。完整代码:

    package main
    
    import (
        "fmt"
        "gopkg.in/yaml.v2"
    )
    
    var str string = `
    'Include':
        - 'string1'
        - 'string2'
    
    'Exclude':
        - 'string3'
        - 'string4'
    `
    
    type Paths struct {
        Include []string `yaml:"Include"`
        Exclude []string `yaml:"Exclude"`
    }
    
    func main() {
        paths := Paths{}
    
        err := yaml.Unmarshal([]byte(str), &paths)
    
        fmt.Printf("%v\n", err)
        fmt.Printf("%+v\n", paths)
    }
    

    【讨论】:

    • 感谢您的回复!我确实按照您在此处的建议尝试使用切片,但我认为由于结构中缺少标签而无法使用。在我能想出更好的东西之前,我想我会在它们加载后将它们变成地图!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-01-17
    • 1970-01-01
    • 2018-03-26
    • 2021-03-13
    • 1970-01-01
    • 2018-07-02
    • 2021-01-11
    相关资源
    最近更新 更多