dtbc37573 2018-02-19 22:04
浏览 239

如何将Yaml键映射到Golang中的结构?

I'm looking to write a go script that can parse through a yaml file. I created a test yaml file with the following:

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

What would the mapping to a struct look like in go?

I've tried along the lines of:

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

But nothing is returned

Any help would be much appreciated

Thanks

  • 写回答

1条回答 默认 最新

  • doulifang5554 2018-02-20 10:15
    关注

    You should iterate over your uppermost yml keys ["Dog", "Cat"] and then put it into the struct. If you put this in your config it outputs the name of the animal:

    name: "Dog"
    
    评论

报告相同问题?

悬赏问题

  • ¥15 目详情-五一模拟赛详情页
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line