dongtuoji5396 2017-07-15 17:27
浏览 32
已采纳

如何使用毒蛇加载地图列表?

I have the following config I want to load with viper:

artist:
  name: The Beatles
  albums:
  - name: The White Album
    year: 1968
  - name: Abbey Road
    year: 1969

I can't work out how to load a list of maps. I guess I need to unmarshal just this key, but this code doesn't work:

type Album struct {
    Name string
    Year int
}

type Artist struct {
    Name string
    Albums []Album
}

var artist Artist
viper.UnmarshalKey("artists", &artist)

What am I missing?

  • 写回答

1条回答 默认 最新

  • drfqfuhej48511519 2017-07-15 18:10
    关注

    Are you sure key is artists in the yaml? Do you mean to supply artist?

    Working example:

    str := []byte(`artist:
      name: The Beatles
      albums:
      - name: The White Album
        year: 1968
      - name: Abbey Road
        year: 1969
    `)
    
        viper.SetConfigType("yaml")
        viper.ReadConfig(bytes.NewBuffer(str))
    
        var artist Artist
        err := viper.UnmarshalKey("artist", &artist)
    
        fmt.Printf("%v, %#v
    ", err, artist)
    

    Output:

    <nil>, main.Artist{Name:"The Beatles", Albums:[]main.Album{main.Album{Name:"The White Album", Year:1968}, main.Album{Name:"Abbey Road", Year:1969}}}
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 求螺旋焊缝的图像处理
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面
  • ¥15 itunes恢复数据最后一步发生错误
  • ¥15 关于#windows#的问题:2024年5月15日的win11更新后资源管理器没有地址栏了顶部的地址栏和文件搜索都消失了