首頁  >  文章  >  後端開發  >  解組 yaml 將 dict 鍵映射到結構屬性

解組 yaml 將 dict 鍵映射到結構屬性

WBOY
WBOY轉載
2024-02-09 15:40:29904瀏覽

解组 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刪除