Golang YAML reading with map of maps

旧城冷巷雨未停 提交于 2021-02-17 21:30:20

问题


Here is my YAML file.

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

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)
}

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


回答1:


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


来源:https://stackoverflow.com/questions/26290485/golang-yaml-reading-with-map-of-maps

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!