Reputation: 151
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?
Upvotes: 1
Views: 5094
Reputation: 46433
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"`
}
Upvotes: 4