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 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度