在Go中将yaml文件解析为预定义的结构

在Go中将yaml文件解析为预定义的结构

本文介绍了在Go中将yaml文件解析为预定义的结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有多个需要解析的yaml文件,它们具有完全相同的结构

 模式:"1.0.0"id:测试版本:"1.2.3"依赖关系:-名称:ui类型:亚军CWD:/ui安装:-名称:api组:测试特性:名称:app网址:appUrl-名称:后端类型:mongoDb路径:是安装:-名称:db类型:蒙哥提供:-名称:api特性:网址:url 

我正在使用

解决方案

您的结构定义应该是这样的

  type Yaml struct {架构字符串ID字符串版本字串依赖[] Dependency}类型Dependency struct {名称字符串类型字符串CWD字串安装[]安装提供[]提供}输入Install struct {名称字符串组字符串类型字符串属性属性}类型属性struct {名称字符串URL字符串}输入Provide struct {名称字符串属性属性} 

这里是完整的示例代码:

 程序包主要进口 ("fmt""io/ioutil"日志""gopkg.in/yaml.v2")var data =`模式:"1.0.0"id:测试版本:"1.2.3"依赖关系:-名称:ui类型:亚军CWD:/ui安装:-名称:api组:测试特性:名称:app网址:appUrl-名称:后端类型:mongoDb路径:是安装:-名称:db类型:蒙哥提供:-名称:api特性:网址:url`输入Yaml struct {架构字符串ID字符串版本字串依赖[] Dependency}类型Dependency struct {名称字符串类型字符串CWD字串安装[]安装提供[]提供}输入Install struct {名称字符串组字符串类型字符串属性属性}类型属性struct {名称字符串URL字符串}输入Provide struct {名称字符串属性属性}func main(){y:= Yaml {}err:= yaml.Unmarshal([] byte(data),& y)如果err!= nil {log.Fatalf(错误:%v",错误)}fmt.Printf(%+ v \ n",y)} 

输出

  {架构:1.0.0 ID:测试版本:1.2.3依赖关系:[{名称:ui类型:运行程序CWD:/ui安装:[{名称:api组:测试类型:属性:{名称:appURL:appUrl}}]提供:[]} {名称:后端类型:mongoDb CWD:安装:[{名称:db组:类型:mongo属性:{名称:URL:}}}]提供:[{名称:api属性:{Name:URL:url}}]}]} 

如果要读取yaml文件,请在主函数中替换:

  err:= yaml.Unmarshal([] byte(data),& y) 

使用

  yamlFile,错误:= ioutil.ReadFile("yaml_sample.yaml")如果err!= nil {log.Printf("yamlFile.Get err#%v",err)}err = yaml.Unmarshal(yamlFile,& y) 

I’ve multiple yaml files which need to be parsed and have exactly the same structure

schema: "1.0.0"
id: test
version: "1.2.3"


dependency :
  - name: ui
    type: runner
    cwd: /ui
    install:
       - name: api
         group: test
         properties:
             name: app
             url: appUrl

  - name: backend
    type: mongoDb
    path: be
    install:
       - name: db
         type: mongo
    provides:
       - name: api
         properties:
            url: url

I am using a yaml parser to parse the files but my question is how in Golang I can build struct that when I parse the doc it will automatically fill the main struct and will include the sub structs (such as dependency/ install sections )

I have tried something like

type main struct {
    schema struct {
        schema  string
        id int
        version string
    }

    dependency struct {
        name  string
        type string
        cwd string

    install struct {
        name  string
    }


}

In the install section, it can be group or type or both and it can have also properties section, so I'm not sure how to buildsome generic /extendable struct which I use to parse the document (the document have close list of properties, what I put in the example describe the most options)

I use this lib to parse the doc

yaml parser

解决方案

Your struct definition should be something like this

type Yaml struct {
    Schema     string
    ID         string
    Version    string
    Dependency []Dependency
}

type Dependency struct {
    Name     string
    Type     string
    CWD      string
    Install  []Install
    Provides []Provide
}

type Install struct {
    Name       string
    Group      string
    Type       string
    Properties Properties
}

type Properties struct {
    Name string
    URL  string
}

type Provide struct {
    Name       string
    Properties Properties
}

Here is full sample code:

package main

import (
    "fmt"
    "io/ioutil"
    "log"

    "gopkg.in/yaml.v2"
)

var data = `
schema: "1.0.0"
id: test
version: "1.2.3"


dependency :
  - name: ui
    type: runner
    cwd: /ui
    install:
       - name: api
         group: test
         properties:
             name: app
             url: appUrl

  - name: backend
    type: mongoDb
    path: be
    install:
       - name: db
         type: mongo
    provides:
       - name: api
         properties:
             url: url
`

type Yaml struct {
    Schema     string
    ID         string
    Version    string
    Dependency []Dependency
}

type Dependency struct {
    Name     string
    Type     string
    CWD      string
    Install  []Install
    Provides []Provide
}

type Install struct {
    Name       string
    Group      string
    Type       string
    Properties Properties
}

type Properties struct {
    Name string
    URL  string
}

type Provide struct {
    Name       string
    Properties Properties
}

func main() {
    y := Yaml{}

    err := yaml.Unmarshal([]byte(data), &y)
    if err != nil {
        log.Fatalf("error: %v", err)
    }
    fmt.Printf("%+v\n", y)

}

Output

{Schema:1.0.0 ID:test Version:1.2.3 Dependency:[{Name:ui Type:runner CWD:/ui Install:[{Name:api Group:test Type: Properties:{Name:appURL:appUrl}}] Provides:[]} {Name:backend Type:mongoDb CWD: Install:[{Name:db Group: Type:mongo Properties:{Name: URL:}}] Provides:[{Name:api Properties:{Name: URL:url}}]}]}

If you want to read from a yaml file, in the main func just replace:

err := yaml.Unmarshal([]byte(data), &y)

with

yamlFile, err := ioutil.ReadFile("yaml_sample.yaml")
if err != nil {
    log.Printf("yamlFile.Get err   #%v ", err)
}
err = yaml.Unmarshal(yamlFile, &y)

这篇关于在Go中将yaml文件解析为预定义的结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 11:34