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

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}}]
    
    已采纳该答案
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题