gpt4 book ai didi

go - 解析 yaml 返回空对象

转载 作者:IT王子 更新时间:2023-10-29 02:10:02 24 4
gpt4 key购买 nike

我有以下 yaml,我需要将其解析为结构。在 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

最佳答案

格式正确的 yaml 是您应该考虑的第一件事。如果你想要一个 Runs,你应该将你的 yaml 格式化成这样

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

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

package main

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

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

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

func main() {

var document Document
reader, err := os.Open("demo.yml")
if err != nil {
log.Fatal(err)
}
buf, _ := ioutil.ReadAll(reader)
yaml.Unmarshal(buf, &document)
if err := yaml.Unmarshal(buf, &document); err != nil {
fmt.Print(err)
os.Exit(1)
}
fmt.Println(document)
}

关于go - 解析 yaml 返回空对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49516571/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com