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

解析嵌套的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"`
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制
  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊
  • ¥15 安装svn网络有问题怎么办
  • ¥15 vue2登录调用后端接口如何实现