【问题标题】:golang parse yaml file struct challengedgolang 解析 yaml 文件结构受到挑战
【发布时间】:2017-01-27 00:38:05
【问题描述】:

解析此类 yaml 文件时出现问题。使用"yaml.v2"

info:  "abc"

data:
  source:  http://intra
  destination:  /tmp

run:
  - id:  "A1"
    exe:  "run.a1"
    output:  "output.A1"

  - id:  "A2"
    exe:  "run.a2"
    output:  "output.A2"

我想获取 YAML 文件的所有值,所以我有一个像这样的基本结构

type Config struct {
  Info  string
  Data struct {
    Source  string `yaml:"source"`
    Destination  string `yaml:"destination"`
    }
 }

这行得通

但是,我不确定如何设置“运行”结构。额外的层让我感到困惑。

type Run struct {
 ...
}

【问题讨论】:

  • 您的 yaml 文件示例无效,使用 Ruby 的 YAML 解析器会导致错误。你想像{"run":[{"id":"A1","exe":"run.a1","output":"output.A1"},{"id":"A2",...}]} 这样的 JSON 格式吗?
  • 固定原始问题

标签: go yaml


【解决方案1】:

OP 的 YAML 示例无效。当run 的值是字典列表时,它应该是这样的:

info:  "abc"

data:
  source:  http://intra
  destination:  /tmp

run:
  - id:  "A1"
    exe:  "run.a1"
    output:  "output.A1"

  - id:  "A2"
    exe:  "run.a2"
    output:  "output.A2"

这是相应的数据结构,以及将 YAML 解码为 golang 结构的示例。

package main

import (
    "fmt"
    "io/ioutil"
    "os"

    yaml "gopkg.in/yaml.v2"
)

type Config struct {
    Info string
    Data struct {
        Source      string
        Destination string
    }
    Run []struct {
        Id     string
        Exe    string
        Output string
    }
}

func main() {
    var conf Config
    reader, _ := os.Open("example.yaml")
    buf, _ := ioutil.ReadAll(reader)
    yaml.Unmarshal(buf, &conf)
    fmt.Printf("%+v\n", conf)
}

运行它会输出(添加了一些缩进以提高可读性):

{Info:abc
 Data:{Source:http://intra Destination:/tmp}
 Run:[{Id:A1 Exe:run.a1 Output:output.A1}
      {Id:A2 Exe:run.a2 Output:output.A2}]

【讨论】:

  • @NinjaGaiden 有时取决于天气:)。为你 +1。
  • 谢谢。我希望今天是晴天
  • 我如何提取、id A1 的、exe 和输出? A2 也一样?
  • @NinjaGaiden A1 的 id 可以通过conf.Run[0].Id 访问。 A2的id可以通过conf.Run[1].Id访问
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-30
  • 1970-01-01
  • 2018-01-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多