golang 解析 yaml 文件结构受到挑战

标签 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"

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

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

这行得通

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

type Run struct {
 ...
}

最佳答案

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}]

关于golang 解析 yaml 文件结构受到挑战,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41885442/

相关文章:

java - 限制客户端仅使用从 yml 文件创建的配置列表中的一个配置

javascript - 如何使用脚本中的引用压缩 YAML 文件?

go - 我应该将 `perm` 参数传递给 ioutil.WriteFile 什么?

list - 如何在 Go 中打印列表的值

go - 如何摆脱时间 sleep

kubernetes - 如何使用heredoc在k8s pod yaml定义中创建yaml文件?

go - shell提示时自动输入定义的密码?

go - Atom Editor Golang - 转到声明不起作用

yaml - yaml 中的 block 标量和流标量有什么区别?

git - Azure DevOps - 条件/表达式允许我跳过阶段内的任务