golang parse yaml文件struct challenged

时间:2017-01-27 00:38:06

标签: go yaml

解析此类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"

我想得到Y​​AML文件的所有值,所以我有一个像这样的基本结构

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

这有效

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

type Run struct {
 ...
}

1 个答案:

答案 0 :(得分: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}]
相关问题