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 蓝桥oj3931,请问我错在哪里
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染