解析yaml返回空对象

时间:2018-03-27 15:11:29

标签: go yaml

我有以下yaml,我需要解析为struct。 在builds属性中,我在调试时得到空值,我在这里缺少什么?

我使用" gopkg.in/yaml.v2"

- name: srv
    type: java
    path: srv
    builds:
     - name: db
        properties:
           JBR_CONFIG_RESOURCE_CONFIG: '[META-INF/context.xml:
              {"service_name" : "~{h-container}"}]'
           TEST2: aaaa

结构是

type Runs struct {
    Name       string
    Type       string
    Path       string     `yaml:"path,omitempty"`
    Builds   []Builds `yaml:”builds,omitempty"`
}

type Builds struct {
    Name       string     `yaml:"name,omitempty"`
    Properties Properties `yaml:"properties,omitempty"`
}

type Properties map[string]string

2 个答案:

答案 0 :(得分:1)

正确格式化的yaml是你应该考虑的第一件事。 如果你想要一个change_column :table, :column, :text, default: [].to_yaml 你应该让你的yaml形成类似的东西

Runs

但是,我想要更多这个对象,你需要将它们分组在一个参数中。它看起来像这样

name: srv
builds:
  -
    name: db
    properties:
      JBR_CONFIG_RESOURCE_CONFIG: "[META-INF/context.xml:
      {\"service_name\" : \"~{h-container}\"}]"
      TEST2: aaaa
path: srv
type: java

然后在你的代码中看起来像这样

runs:
  -
    name: srv
    builds:
      -
        name: db
        properties:
          JBR_CONFIG_RESOURCE_CONFIG: "[META-INF/context.xml:
          {\"service_name\" : \"~{h-container}\"}]"
          TEST2: aaaa
    path: srv
    type: java
  -
    name: srv2
    builds:
      -
        name: db2
        properties:
          JBR_CONFIG_RESOURCE_CONFIG: "[META-INF/context.xml:
          {\"service_name\" : \"~{h-container}\"}]"
          TEST2: aaaa2
    path: srv2
    type: java2

答案 1 :(得分:0)

确保您的yaml文件格式正确。请查看此tool

下面这段代码工作正常。

package main

import (
    "fmt"
    "gopkg.in/yaml.v2"
    "log"
)

type Runs struct {
    Name   string
    Type   string
    Path   string   `yaml:"path,omitempty"`
    Builds []Builds `yaml:”builds,omitempty"`
}

type Builds struct {
    Name       string     `yaml:"name,omitempty"`
    Properties Properties `yaml:"properties,omitempty"`
}

type Properties map[string]string

func main() {
    data := `builds: 
  - 
    name: db
    properties: 
      JBR_CONFIG_RESOURCE_CONFIG: "[META-INF/context.xml: {\"service_name\" : \"~{h-container}\"}]"
      TEST2: aaaa
name: srv
path: srv
type: java
`

    runs := Runs{}

    err := yaml.Unmarshal([]byte(data), &runs)
    if err != nil {
        log.Fatalf("error: %v", err)
    }
    fmt.Printf("--- t:\n%v\n\n", runs)
    d, err := yaml.Marshal(&runs)
    if err != nil {
        log.Fatalf("error: %v", err)
    }
    fmt.Printf("--- t dump:\n%s\n\n", string(d))
}

我希望这有帮助!