带有地图的Golang YAML阅读 [英] Golang YAML reading with map of maps

查看:64
本文介绍了带有地图的Golang YAML阅读的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的YAML文件.

Here is my YAML file.

description: fruits are delicious
fruits:
  apple:
    - red
    - sweet
  lemon:
    - yellow
    - sour

我可以使用 gopkg.in/yaml.v1 包来阅读一个更扁平的版本,但是我一直试图弄清楚如何在看起来像一个YAML文件的情况下读取该文件.地图.

I can read a flatter version of this with the gopkg.in/yaml.v1 package but I'm stuck trying to figure out how to read this YAML file when it's got what seems like a map of maps.

package main

import (
  "fmt"
  "gopkg.in/yaml.v1"
  "io/ioutil"
  "path/filepath"
)

type Config struct {
  Description string
  Fruits []Fruit
}

type Fruit struct {
  Name string
  Properties []string
}

func main() {
  filename, _ := filepath.Abs("./file.yml")
  yamlFile, err := ioutil.ReadFile(filename)

  if err != nil {
    panic(err)
  }

  var config Config

  err = yaml.Unmarshal(yamlFile, &config)
  if err != nil {
    panic(err)
  }

  fmt.Printf("Value: %#v\n", config.Description)
  fmt.Printf("Value: %#v\n", config.Fruits)
}

它无法取出嵌套的水果.好像又回来了.值:[] main.Fruit(nil).

It can't get the nested Fruits out. It seems to come back empty. Value: []main.Fruit(nil).

推荐答案

使用字符串切片图表示水果属性:

Use a map of string slices to represent the fruit properties:

type Config struct {
  Description string
  Fruits map[string][]string
}

使用以下命令打印未编组的配置

Printing the unmarshaled configuration with

fmt.Printf("%#v\n", config)

产生以下输出(不包括为可读性而添加的空白):

produces the following output (not including the whitespace I added for readability):

main.Config{Description:"fruits are delicious", 
     Fruits:map[string][]string{
          "lemon":[]string{"yellow", "sour"}, 
          "apple":[]string{"red", "sweet"}}}

这篇关于带有地图的Golang YAML阅读的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆