gpt4 book ai didi

使用映射将 YAML 解码到结构中

转载 作者:数据小太阳 更新时间:2023-10-29 03:26:45 26 4
gpt4 key购买 nike

我正在尝试将 YAML 文件解码为包含两个映射的结构(使用 go-yaml)。

YAML 文件:

'Include':
- 'string1'
- 'string2'

'Exclude':
- 'string3'
- 'string4'

结构:

type Paths struct {
Include map[string]struct{}
Exclude map[string]struct{}
}

尝试解码的函数的简化版本(即删除了错误处理等):

import "gopkg.in/yaml.v2"

func getYamlPaths(filename string) (Paths, error) {
loadedPaths := Paths{
Include: make(map[string]struct{}),
Exclude: make(map[string]struct{}),
}

filenameabs, _ := filepath.Abs(filename)
yamlFile, err := ioutil.ReadFile(filenameabs)

err = yaml.Unmarshal(yamlFile, &loadedPaths)
return loadedPaths, nil
}

正在从文件中读取数据,但解码函数未将任何内容放入结构中,并且未返回任何错误。

我怀疑 unmarshal-function 无法将 YAML 集合转换为 map[string]struct{},但如前所述,它没有产生任何错误,我四处寻找类似的问题,似乎找不到。

任何线索或见解将不胜感激!

最佳答案

通过调试,我发现了多个问题。首先,yaml 似乎并不关心字段名称。您必须

注释字段
`yaml:"NAME"`

其次,在YAML文件中,IncludeExclude都只包含一个字符串列表,而不是类似map的东西。所以你的结构变成:

type Paths struct {
Include []string `yaml:"Include"`
Exclude []string `yaml:"Exclude"`
}

而且它有效。完整代码:

package main

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

var str string = `
'Include':
- 'string1'
- 'string2'

'Exclude':
- 'string3'
- 'string4'
`

type Paths struct {
Include []string `yaml:"Include"`
Exclude []string `yaml:"Exclude"`
}

func main() {
paths := Paths{}

err := yaml.Unmarshal([]byte(str), &paths)

fmt.Printf("%v\n", err)
fmt.Printf("%+v\n", paths)
}

关于使用映射将 YAML 解码到结构中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39176968/

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