drt3751
2018-07-13 13:22
浏览 463
已采纳

解析嵌套的YAML Golang

I'm trying to parse a simple YAML file with go, but I am having some difficulty.

My YAML file is as follows.

key1:
    attr1: "attr1"
    attr2: "attr2"
    attr3: "attr3"
    list1: ["a", "b", "c"]
    list2: ["d", "e", "f"]

and my go script looks like this.

package main

import (
    "fmt"
    "io/ioutil"
    "log"

    "gopkg.in/yaml.v2"
)

type keys struct {
    Key1 map[string]key1 `yaml:"key1"`
}

type key1 struct {
    Attr1 string   `yaml:"attr1"`
    Attr2 string   `yaml:"attr2"`
    Attr3 string   `yaml:"attr3"`
    List1 []string `yaml:"list1"`
    List2 []string `yaml:"list2"`
}

func main() {
    var d keys

    source, err := ioutil.ReadFile("test_yaml.yaml")

    if err != nil {
        log.Fatal("Couldn't read yaml file.")
    }

    err = yaml.Unmarshal(source, &d)

    if err != nil {
        log.Fatal("Couldn't parse yaml file.")
    }

    fmt.Println(d)
}

When I run it, my map is empty ({map[]} is printed). If I change the keys struct to map[string]interface{} it seems to get all the info, but the lists aren't interpreted correctly, which is why I tried defining the inner structure.

Does anyone know why my key1 struct doesn't work but interface{} does?

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dpyln64620 2018-07-13 13:26
    已采纳

    Your type definition:

    type keys struct {
        Key1 map[string]key1 `yaml:"key1"`
    }
    
    type key1 struct {
        Attr1 string   `yaml:"attr1"`
        Attr2 string   `yaml:"attr2"`
        Attr3 string   `yaml:"attr3"`
        List1 []string `yaml:"list1"`
        List2 []string `yaml:"list2"`
    }
    

    Implies this structure:

    key1:
        stuff:
            attr1: "attr1"
            attr2: "attr2"
            attr3: "attr3"
            list1: ["a", "b", "c"]
            list2: ["d", "e", "f"]
        morestuff:
            attr1: "attr1"
            attr2: "attr2"
            attr3: "attr3"
            list1: ["a", "b", "c"]
            list2: ["d", "e", "f"]
    

    Because, per your data type, key1 should contain a map of keys to structs - adding a level to the hierarchy that doesn't exist. For the YAML you posted, your structure should be:

    type keys struct {
        Key1 key1 `yaml:"key1"`
    }
    
    type key1 struct {
        Attr1 string   `yaml:"attr1"`
        Attr2 string   `yaml:"attr2"`
        Attr3 string   `yaml:"attr3"`
        List1 []string `yaml:"list1"`
        List2 []string `yaml:"list2"`
    }
    
    已采纳该答案
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题