dqc18251 2017-01-27 00:38
浏览 160
已采纳

挑战golang解析yaml文件结构

Having a problem parsing this sort of yaml file. Using "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"

I would like to get all the values of the YAML file so I have a basic struct like this

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

This works

But, I am not sure how to setup the struct for "run". The extra layer is confusing me.

type Run struct {
 ...
}
  • 写回答

1条回答 默认 最新

  • doushu2699 2017-01-27 01:57
    关注

    the OP's example of YAML is invalid. When value of run is list of dictionary it should be something like this:

    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"
    

    And here's the corresponding data struture, and example for decoding YAML into golang's structure.

    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
    ", conf)
    }
    

    running this will output (added some indent for readability):

    {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}]
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题