
php小编西瓜今天为大家介绍一种非常有用的技巧——将 YAML 解组为字典,并将键映射到结构属性。YAML 是一种轻量级的数据序列化格式,常用于配置文件和数据交换。通过解组 YAML,我们可以将其转换为字典,然后将字典的键映射到结构属性,方便我们在代码中进行进一步的操作和处理。这种技巧在处理配置文件或者从外部数据源加载数据时非常实用,让我们一起来看看具体的实现方法吧!
我确实在这里搜索了一段时间,但没有找到合适的答案:
我正在尝试将 yaml dict 键解组到结构的属性而不是映射的键上。 给定这个 yaml
commands:
php:
service: php
bin: /bin/php
node:
service: node
bin: /bin/node
我能够将其解组为如下结构:
type config struct {
commands map[string]struct {
service string
bin string
}
}
但是我怎样才能将它解组成这样的结构:
type Config struct {
Commands []struct {
Name string // <-- this should be key from the yaml (i.e. php or node)
Service string
Bin string
}
}
提前感谢您的帮助
您可以编写一个自定义解组器,如下所示(在 go playground 上):
package main
import (
"fmt"
"gopkg.in/yaml.v3"
)
var input []byte = []byte(`
commands:
php:
service: php
bin: /bin/php
node:
service: node
bin: /bin/node
`)
type Command struct {
Service string
Bin string
}
type NamedCommand struct {
Command
Name string
}
type NamedCommands []NamedCommand
type Config struct {
Commands NamedCommands
}
func (p *NamedCommands) UnmarshalYAML(value *yaml.Node) error {
if value.Kind != yaml.MappingNode {
return fmt.Errorf("`commands` must contain YAML mapping, has %v", value.Kind)
}
*p = make([]NamedCommand, len(value.Content)/2)
for i := 0; i < len(value.Content); i += 2 {
var res = &(*p)[i/2]
if err := value.Content[i].Decode(&res.Name); err != nil {
return err
}
if err := value.Content[i+1].Decode(&res.Command); err != nil {
return err
}
}
return nil
}
func main() {
var f Config
var err error
if err = yaml.Unmarshal(input, &f); err != nil {
panic(err)
}
for _, cmd := range f.Commands {
fmt.Printf("%+v\n", cmd)
}
}
我已将命令数据拆分为 command 和 namedcommand 以使代码更简单,因为您只需调用 decode 即可提供嵌入的 command 结构体的值。如果所有内容都在同一个结构中,则需要手动将键映射到结构字段。
以上就是解组 yaml 将 dict 键映射到结构属性的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号