这是我的YAML文件.

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

我可以用gopkg.in/yaml.v1包阅读更平坦的版本,但是当这个YAML文件看起来像是 map 时,我却无法理解如何阅读它.

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)美元.

推荐答案

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

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

使用打印未编组的配置

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

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

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

Go相关问答推荐

区分Terminal和Hook Zerolog Go中的错误级别日志(log)输出

使用Gorm创建自定义连接表

如何将泛型函数作为参数传递给golang中的另一个函数?

如何描述OpenAPI规范中围棋的数据类型.JSON?

golang.org/x/oauth2 oauth2.Config.Endpoint.TokenURL mock:缺少access_token

将类型定义为泛型类型实例化

如何在v2 Go SDK中使用KeyConditionExpression查询AWS DynamoDb?

如何修复 Go 中协议缓冲区定义中重新定义的字段?

一个Go module可以和之前的非module模块发布在同一个路径下吗?

golang gin 获取 cookie json

如何在 `hashicorp / terraform-exec` 中将 `ApplyConfig` 传递给 `tf.Apply()`?

如何使用名称具有包名称的嵌套 struct 启动 go struct

没有任务角色的 AWS CDK ECS 任务定义

在恒等函数中将类型 T 转换为类型 U

如何使用 math/big 对 bigInt 进行取模?

如何在 Windows 中使用 github.com/AllenDang/giu 和 github.com/gordonklaus/portaudio 构建 GO 程序

如何在眼镜蛇(golang)中将标志作为参数传递?

带有 grpc 的 protobuf 用于拆分包中的 Go

退格字符在围棋操场中不起作用

如何解决在mac m1中运行gcc失败退出状态1?