登录
首页 >  Golang >  Go问答

将 YAML 解组为有序映射

来源:stackoverflow

时间:2024-03-30 12:18:30 387浏览 收藏

各位小伙伴们,大家好呀!看看今天我又给各位带来了什么文章?本文标题《将 YAML 解组为有序映射》,很明显是关于Golang的文章哈哈哈,其中内容主要会涉及到等等,如果能帮到你,觉得很不错的话,欢迎各位多多点评和分享!

问题内容

我正在尝试使用 go yaml v3 解组以下 yaml。

model:
  name: mymodel
  default-children:
  - payment

  pipeline:
    accumulator_v1:
      by-type:
        type: static
        value: false
      result-type:
        type: static
        value: 3

    item_v1:
      amount:
        type: schema-path
        value: amount
      start-date:
        type: schema-path
        value: start-date

管道下是任意数量的有序项目。应将其解组到的结构如下所示:

type PipelineItemOption struct {
        Type string
        Value interface{}
}

type PipelineItem struct {
        Options map[string]PipelineItemOption
}

type Model struct {
        Name string
        DefaultChildren []string `yaml:"default-children"`
        Pipeline orderedmap[string]PipelineItem    // "pseudo code"
}

这如何与 golang yaml v3 配合使用?在 v2 中,有 mapslice,但在 v3 中消失了。


解决方案


您声称编组到中间 yaml.node 是高度非通用的,但我真的不明白为什么。它看起来像这样:

package main

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

type pipelineitemoption struct {
        type string
        value interface{}
}

type pipelineitem struct {
    name string
        options map[string]pipelineitemoption
}

type pipeline []pipelineitem

type model struct {
        name string
        defaultchildren []string `yaml:"default-children"`
        pipeline pipeline
}

func (p *pipeline) unmarshalyaml(value *yaml.node) error {
    if value.kind != yaml.mappingnode {
        return fmt.errorf("pipeline must contain yaml mapping, has %v", value.kind)
    }
    *p = make([]pipelineitem, 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.options); err != nil {
            return err
        }
    }
    return nil
}


var input []byte = []byte(`
model:
  name: mymodel
  default-children:
  - payment

  pipeline:
    accumulator_v1:
      by-type:
        type: static
        value: false
      result-type:
        type: static
        value: 3

    item_v1:
      amount:
        type: schema-path
        value: amount
      start-date:
        type: schema-path
        value: start-date`)

func main() {
    var f struct {
        model model
    }
    var err error
    if err = yaml.unmarshal(input, &f); err != nil {
        panic(err)
    }
    fmt.printf("%v", f)
}

对我来说,弄清楚 v3 而不是 mapslice 的期望是一个学习曲线。与 @flyx 的回答类似,需要遍历 yaml.node 树,特别是它的 []content

这里是一个实用程序,用于提供有序的 map[string] 接口{},它的可重用性和整洁性更高一些。 (尽管它并不像指定的问题那样受到限制。)

根据上述结构,一般重新定义 pipeline

type model struct {
    name string
    defaultchildren []string `yaml:"default-children"`
    pipeline *yaml.node
}

使用实用程序 fn 遍历 yaml.node 内容:

// fragment
var model model
if err := yaml.unmarshal(&model) ; err != nil {
    return err
}

om, err := getorderedmap(model.pipeline)
if err != nil {
    return err
}

for _,k := range om.order {
    v := om.map[k]
    fmt.printf("%s=%v\n", k, v)
}

实用程序 fn:

type OrderedMap struct {
    Map map[string]interface{}
    Order []string
}

func getOrderedMap(node *yaml.Node) (om *OrderedMap, err error) {
    content := node.Content
    end := len(content)
    count := end / 2

    om = &OrderedMap{
        Map: make(map[string]interface{}, count),
        Order: make([]string, 0, count),
    }
    
    for pos := 0 ; pos < end ; pos += 2 {
        keyNode := content[pos]
        valueNode := content[pos + 1]

        if keyNode.Tag != "!!str" {
            err = fmt.Errorf("expected a string key but got %s on line %d", keyNode.Tag, keyNode.Line)
            return
        }

        var k string
        if err = keyNode.Decode(&k) ; err != nil {
            return
        }

        var v interface{}
        if err = valueNode.Decode(&v) ; err != nil {
            return
        }

        om.Map[k] = v
        om.Order = append(om.Order, k)
    }

    return
}

今天带大家了解了的相关知识,希望对你有所帮助;关于Golang的技术知识我们会一点点深入介绍,欢迎大家关注golang学习网公众号,一起学习编程~

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>