英文:
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"}}}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论