go - 解析地图的 yaml 错误
问题描述
我有以下程序,我需要在其中使用以下结构解析 yaml
https://codebeautify.org/yaml-validator/cbabd352 这是有效的 yaml,我使用 byte 使其更简单,可能在复制粘贴到问题期间缩进已更改,但您可以在链接中看到 yaml 有效
yaml 有一个 api_version 和跑步者,对于每个跑步者(键是名字)我有一个命令列表,我需要打印这些命令function1
,function4
我在这里做错了什么?
package main
import (
"fmt"
"log"
"gopkg.in/yaml.v2"
)
var runContent = []byte(`
api_ver: 1
runners:
- name: function1
type:
- command: spawn child process
- command: build
- command: gulp
- name: function2
type:
- command: run function 1
- name: function3
type:
- command: ruby build
- name: function4
type:
- command: go build
`)
type Result struct {
Version string `yaml:"api_ver"`
Runners []Runners `yaml:"runners"`
}
type Runners struct {
Name string `yaml:"name"`
Type []Command `yaml:"type"`
}
type Command struct {
Command string `yaml:"command"`
}
func main() {
var runners []Result
err := yaml.Unmarshal(runContent, &runners)
if err != nil {
log.Fatalf("Error : %v", err)
}
fmt.Printf("%+v", runners[0])
}
我得到的错误cannot unmarshal !!map into []main.Result
我无法更改 yaml,它应该完全像这样
解决方案
您提供的 yaml 包含令牌错误。在此处验证代码中使用的 yaml https://codebeautify.org/yaml-validator/cbaabb32
之后创建结构类型结果的变量而不是数组。因为您使用的 yaml 正在使用 Runners 数组和 api_version 创建一个结构。
这个
var runners []Result
应该
var runners Result
因为因为结构不是切片。获取 yaml 中使用的函数名称的命令列表。您需要遍历 runners 数组以查找函数的名称并获取该函数的命令值。下面是工作代码:
package main
import (
"fmt"
"log"
"gopkg.in/yaml.v2"
)
var runContent = []byte(`
api_ver: 1
runners:
- name: function1
type:
- command: spawn child process
- command: build
- command: gulp
- name: function2
type:
- command: run function 1
- name: function3
type:
- command: ruby build
- name: function4
type:
- command: go build
`)
type Result struct {
Version string `yaml:"api_ver"`
Runners []Runners `yaml:"runners"`
}
type Runners struct {
Name string `yaml:"name"`
Type []Command `yaml:"type"`
}
type Command struct {
Command string `yaml:"command"`
}
func main() {
var runners Result
// parse mta yaml
err := yaml.Unmarshal(runContent, &runners)
if err != nil {
log.Fatalf("Error : %v", err)
}
commandList := getCommandList("function1", runners.Runners)
fmt.Printf("%+v", commandList)
}
func getCommandList(name string, runners []Runners) []Command {
var commandList []Command
for _, value := range runners {
if value.Name == name {
commandList = value.Type
}
}
return commandList
}
推荐阅读
- python - FMUException: 未能设置实验
- javascript - 我应该绑定内置的 React 方法吗?
- wso2 - WSO2IS - 将验证码添加到密码重置流程
- qt - 如何通过 DEFINE 在 qt .pro 文件中添加路径
- apache-spark - Dataproc Spark Job 崩溃后无法找到 JVM 致命错误日志文件 (hs_err_pid.log)
- reactjs - 反应钩子。无法对未安装的组件执行 React 状态更新
- java - 如何清理 Java 飞行记录
- java - 如何快速得到计数结果?
- kubernetes - 在 Kubernetes 中保持 pod 卷挂载可配置
- java - 如何使用 gson 或其他 Java 库从包含 json 的字符串中提取字段