You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将YAML反序列化为含string与Source结构体的复杂Go对象?

如何将YAML反序列化为包含自定义结构体的复杂映射类型

核心需求是将YAML反序列化为map[string]map[interface{}]string这类复杂对象,需要区分interface{}部分是string类型还是自定义的Source结构体类型。由于YAML无法自动将数据反序列化为Source结构体,需要实现yaml.Unmarshaler接口,但对反序列化流程不熟悉,仅推测需要手动遍历*yaml.Node并调用UnmarshalYAML方法。

定义的结构体与可能的类型变体

type Source struct {
    ID     string `yaml:"id"`
    Name   string `yaml:"name"`
    LogoID string `yaml:"logoId"`
    URL    string `yaml:"url"`
}

type UNFT struct {
    ItemMeta map[string]map[interface{}]string `yaml:"item_meta"`
    // 实际场景中该字段可能是以下两种类型之一
    // ItemMeta map[string]map[string]string `yaml:"item_meta"`
    // ItemMeta map[string]map[Source]string `yaml:"item_meta"`
}

自定义反序列化所需接口

要实现自定义反序列化逻辑,需要满足yaml.Unmarshaler接口:

type Unmarshaler interface {
    UnmarshalYAML(value *yaml.Node) error
}

完整示例代码

package main

import (
    "fmt"

    "gopkg.in/yaml.v3"
)

type Source struct {
    ID     string `json:"id"`
    Name   string `json:"name"`
    LogoID string `json:"logoId"`
    URL    string `json:"url"`
}

var data = `
unf:
    item_meta:
      source:
           !struct
           ? id: "data-watch" 
             name: "DataWatch"
             logoid: "data-watch"
             url: "https"
           : "product_any('SS')"
      public_usage:
        "": "source_any('SDF')"
        "provider": "source_any('ANO')"`

type UNFT struct {
    ItemMeta map[string]map[interface{}]string `yaml:"item_meta"`
}

type MetaConverterConfigT struct {
    UNFT UNFT `yaml:"unf"`
}

func main() {
    cfg := MetaConverterConfigT{}

    err := yaml.Unmarshal([]byte(data), &cfg)
    if err != nil {
        fmt.Printf("%w", err)
    }

    fmt.Println(cfg)
}

func (s *UNFT) UnmarshalYAML(n *yaml.Node) error {
    var cfg map[string]map[interface{}]string
    if err := n.Decode(&cfg); err != nil {
        fmt.Printf("%w", err)
    }

    return nil
}

内容的提问来源于stack exchange,提问作者Bob

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 13:50:40