【问题标题】:How to map yaml keys to structs in golang?如何将yaml键映射到golang中的结构?
【发布时间】:2018-07-30 04:52:32
【问题描述】:

我希望编写一个可以解析 yaml 文件的 go 脚本。我使用以下内容创建了一个测试 yaml 文件:

    Dog:
      - name: "Dog"
      - secrets:
          username: "Shiba"
          password: "inu"
          color: "yellow"
    Cat:
      - name: "Cat"
      - secrets:
          words: "meow"
          color: "black"

在 go 中映射到结构会是什么样子?

我已经尝试过:

            package main

            import (
                "fmt"
                "log"

                "github.com/spf13/viper"
            )

            type Animal struct {
                Animal  []string
                Name    string
                Secrets []map[string]string
            }

            func main() {
                viper.SetConfigName("demo")
                viper.AddConfigPath(".")
                viper.SetConfigType("yaml")

                err := viper.ReadInConfig()

                if err != nil {
                    log.Fatal(err)
                }

                var animal Animal
                err = viper.Unmarshal(&animal)
                if err != nil {
                    log.Fatal(err)
                }

                fmt.Println(animal.Name)
            }

但是什么都没有返回

任何帮助将不胜感激

谢谢

【问题讨论】:

  • 对于 Viper,我以为你打电话给 viper.ReadInConfig(),而不是解组 - 但我可能是错的
  • 查看go-yaml
  • 我不认为你的意思是“结构的键”——键通常是具体的类型,比如字符串或整数。

标签: go yaml


【解决方案1】:

您应该遍历最上面的 yml 键 ["Dog", "Cat"],然后将其放入结构中。如果你把它放在你的配置中,它会输出动物的名字:

name: "Dog"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-06-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-26
    • 2012-01-07
    • 2015-02-17
    相关资源
    最近更新 更多