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}}]
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法