首页 > 后端开发 > Golang > 正文

解组 yaml 将 dict 键映射到结构属性

WBOY
发布: 2024-02-09 15:40:29
转载
923 人浏览过

解组 yaml 将 dict 键映射到结构属性

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)
    }
}
登录后复制

我已将命令数据拆分为 commandnamedcommand 以使代码更简单,因为您只需调用 decode 即可提供嵌入的 command 结构体的值。如果所有内容都在同一个结构中,则需要手动将键映射到结构字段。

以上是解组 yaml 将 dict 键映射到结构属性的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:stackoverflow.com
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!