2016-08-27 2 views
0

두 맵을 포함하는 구조체로 YAML 파일을 비 정렬 화하려고합니다 (go-yaml 사용).맵으로 구조체로 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이 구조체에 아무 것도 넣지 않고 리턴합니다. 오류 없음.

unmarshal-function이 YAML 콜렉션을 map[string]struct{}으로 바꿀 수는 없지만, 언급 한대로 오류가 발생하지 않으며 비슷한 문제가 있는지 살펴 보았습니다. 찾을 수없는 것 같습니다.

모든 단서 또는 통찰력을 제공해 주시면 감사하겠습니다.

답변

0

디버깅을 통해 여러 문제가 발견되었습니다. 첫째, yaml은 필드 이름을 신경 쓰지 않는 것 같습니다. 당신은 IncludeExclude 모두 문자열 목록 만,지도에 유사하지 뭔가를 포함는 YAML 파일에하는

`yaml:"NAME"` 

두 번째로 필드에 주석을이 . 따라서 구조는 다음과 같습니다.

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) 
} 
+0

답장을 보내 주셔서 감사합니다. 내가 여기에 제안했듯이 슬라이스를 사용하여 시도했지만 구조체의 태그 부족으로 인해 작동하지 않는다고 가정합니다. 내가 뭔가를 더 잘 생각해 낼 때까지 나는 그들이로드 된 후에지도로 변환 할 것입니다! – henrheid