简体   繁体   中英

Parse Nested 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?

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"`
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM