【问题标题】:GoLang - Iterate over data to unmarshal multiple YAML structuresGoLang - 遍历数据以解组多个 YAML 结构
【发布时间】:2015-03-30 18:29:05
【问题描述】:

我是 Golang 的新手,请原谅我的新手。

我目前正在使用 yaml.v2 包 (https://github.com/go-yaml/yaml) 将 YAML 数据解组到结构中。

考虑以下示例代码:

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:\n%+v\n\n", container)

}

结果:

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

正如预期的那样,unmarshal 函数找到了 YAML 数据的一次出现。

我想做的是编写一个简单的 while/each/for 循环,该循环遍历数据变量并将所有出现的事件编组到单独的 Container 结构中。我怎样才能做到这一点?

【问题讨论】:

    标签: go yaml


    【解决方案1】:

    完成您想要的一个简单更改是让yaml 中的数据成为数组中的项目,然后解组为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:\n%+v\n\n", 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}}]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多