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

挑战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 {
 ...
}

图片转代码服务由CSDN问答提供 功能建议

解析此类Yaml文件时遇到问题。 使用“ yaml.v2”

 < 代码>信息:“ abc” 
 
数据:
源:http:// intra 
目标:/ tmp 
 
run:
-id:“ A1” 
 exe:“ run.a1” \  n输出:“ output.A1” 
 
-id:“ A2” 
 exe:“ run.a2” 
输出:“ output.A2” 
   
 
  

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

  type Config结构{
信息字符串
数据结构{  
源字符串`yaml:“源”`
目标字符串`yaml:“目的地”`
} 
} 
   
 
 

这有效

但是,我不确定如何为“运行”设置结构。 多余的一层使我感到困惑。

  type运行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}]
    
    已采纳该答案
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题