dou4121 2016-08-27 02:47
浏览 66
已采纳

使用地图将YAML编组为结构

I'm attempting to unmarshal a YAML file into a struct containing two maps (using go-yaml).

YAML-file:

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

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

The struct:

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

A simplified version (i.e. removed error handling etc.) of the function attempting to unmarshal:

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
}

Data is being read from the file, but the unmarshal-function is not putting anything into the struct, and is returning no errors.

I suspect that the unmarshal-function cannot turn the YAML collections into map[string]struct{}, but as mentioned it is producing no errors, and I've looked around for similar issues and can't seem to find any.

Any clues or insight would be much appreciated!

  • 写回答

1条回答 默认 最新

  • douhao123457 2016-08-27 03:03
    关注

    Through debugging I found multiple problems. First, yaml doesn't seem to care about the fields names. You have to annotate the fields with a

    `yaml:"NAME"`
    

    Second, in the YAML file, Include and Exclude both contain only a list of strings, not something similar to a map. So your struct becomes:

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

    And it works. Full code:

    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
    ", err)
        fmt.Printf("%+v
    ", paths)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog