使用Golang读取包含嵌套映射的YAML文件。

huangapple go评论106阅读模式
英文:

Golang YAML reading with map of maps

问题

这是我的YAML文件。

description: 水果很美味
fruits:
  apple:
    - 红色
    - 甜的
  lemon:
    - 黄色
    - 酸的

我可以使用gopkg.in/yaml.v1包读取这个文件的扁平版本,但是我在尝试读取这个似乎有嵌套映射的YAML文件时遇到了困难。

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

它无法获取嵌套的水果。似乎返回的是空的。Value: []main.Fruit(nil)

英文:

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

得分: 20

使用字符串切片的映射来表示水果属性:

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

使用以下代码打印解析后的配置:

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

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

main.Config{Description:"水果很美味",
     Fruits:map[string][]string{
          "lemon":[]string{"黄色", "酸味"},
          "apple":[]string{"红色", "甜味"}}}
英文:

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

huangapple
  • 本文由 发表于 2014年10月10日 09:20:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/26290485.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定