dongque20030402 2015-03-30 18:29
浏览 299
已采纳

GoLang-遍历数据以解组多个YAML结构

I am fairly new to Golang, please excuse my newbyness.

I am currently using yaml.v2 package (https://github.com/go-yaml/yaml) to unmarshal YAML data into structs.

Consider the following example code:

package main

import (
  "fmt"
  "gopkg.in/yaml.v2"
  "log"
)

type Container struct {
  First  string
  Second struct {
    Nested1 string
    Nested2 string
    Nested3 string
    Nested4 int
  }
}

var data = `
  first: first value
  second:
    nested1: GET
    nested2: /bin/bash
    nested3: /usr/local/bin/customscript
    nested4: 8080

  first: second value
  second:
    nested1: POST
    nested2: /bin/ksh
    nested3: /usr/local/bin/customscript2
    nested4: 8081
`

func main() {

  container := Container{}

  err := yaml.Unmarshal([]byte(data), &container)
  if err != nil {
    log.Fatalf("error: %v", err)
  }
  fmt.Printf("---values found:
%+v

", container)

}

The result:

---values found: {First:second value Second:{Nested1:POST Nested2:/bin/ksh Nested3:/usr/local/bin/customscript2 Nested4:8081}}

This is as expected, the unmarshal function finds one occurrence of the YAML data.

What I would like to do is write a simple while/each/for loop that loops through the data variable and marshals all the occurrences into seperate Container structs. How could I achieve this?

  • 写回答

1条回答 默认 最新

  • dpp3047 2015-03-30 19:57
    关注

    A simple change to accomplish what you want is to have the data in the yaml be items in an array, then Unmarshal into a slice of Container

    var data = `
    - first: first value
      second:
        nested1: GET
        nested2: /bin/bash
        nested3: /usr/local/bin/customscript
        nested4: 8080
    
    - first: second value
      second:
        nested1: POST
        nested2: /bin/ksh
        nested3: /usr/local/bin/customscript2
        nested4: 8081
    `
    
    func main() {
    
        container := []Container{}
    
        err := yaml.Unmarshal([]byte(data), &container)
        if err != nil {
            log.Fatalf("error: %v", err)
        }
        fmt.Printf("---values found:
    %+v
    
    ", container)
    
    }
    
    ---values found:
    [{First:first value Second:{Nested1:GET Nested2:/bin/bash Nested3:/usr/local/bin/customscript Nested4:8080}} {First:second value Second:{Nested1:POST Nested2:/bin/ksh Nested3:/usr/local/bin/customscript2 Nested4:8081}}]
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)