登录
首页 >  Golang >  Go问答

将通用映射转换为 YAML。 Go语言

来源:stackoverflow

时间:2024-04-18 11:45:34 354浏览 收藏

Golang小白一枚,正在不断学习积累知识,现将学习到的知识记录一下,也是将我的所得分享给大家!而今天这篇文章《将通用映射转换为 YAML。 Go语言》带大家来了解一下##content_title##,希望对大家的知识积累有所帮助,从而弥补自己的不足,助力实战开发!


问题内容

所以,我正在开发一个程序,您必须生成 yaml 文件,该文件表示给定目录位置的目录树(path)。例如..

sc
├── file.go
├── file_test.go
└── src
    ├── deploy
    │   ├── deploy.go
    │   └── deploy_test.go
    ├── pod.go
    └── pod_test.go

这应该转换成

sc:
  filetest: "true"
  src:
    deploy:
      deploytest: "true"
  podtest: "true"

请注意,上面仅选择带有 _test 的文件(这是有条件的,问题不大)。我的问题是如何从可以通过 yaml 表示的目录树生成通用 map[string]interface{} 类型的地图。我尝试编写 dfs 实现来遍历树并生成 n-ary 树。其输出如下。我得到了树的根 node 对象。

name: sc
children:
- name: file.go
  children: []
- name: file_test.go
  children: []
- name: src
  children:
  - name: deploy
    children:
    - name: deploy.go
      children: []
    - name: deploy_test.go
      children: []
  - name: pod.go
    children: []
  - name: pod_test.go
    children: []

但正如您所看到的,它是 unmarshalled 使用代表每个节点的数据类型。

//node is the datatype which stores information regarding the file/directory
type node struct {
    name     string
    path     string
    children []*node
}

我想要一个通用的 yaml,其中每个键都不同。有任何想法吗?像这样的事情会有帮助。

func (node *node) tomap() map[string]interface{}{
 //logic
}

生成树的dfs代码

func IteratePath(path string) {
    rootFile, err := os.Stat(path)
    if err != nil {
        logrus.Error("Path : ", path, " doesn't exist. ", err)
    }
    rootfile := ToFile(rootFile, path)
    stack := []*tree.Node{rootfile}
    for len(stack) > 0 {
        file := stack[len(stack)-1]
        stack = stack[:len(stack)-1]
        children, _ := ioutil.ReadDir(file.Path)
        for _, chld := range children {
            child := ToFile(chld, filepath.Join(file.Path, chld.Name()))
            file.Children = append(file.Children, child)
            stack = append(stack, child)
        }
    }

func ToFile(file os.FileInfo, path string) *tree.Node {
    outFile := tree.Node{
        Name:     file.Name(),
        Children: []*tree.Node{},
        Path:     path,
    }
    return &outFile
}

解决方案


您已经在使用递归(使用堆栈变量而不是调用堆栈),那么为什么不再次使用递归将树转换为嵌套映射。这是我编写的从节点开始执行此操作的方法(基于上面的 node 结构):

树嵌套map方法:

type Node struct {
    Name     string
    Children []*Node
}

func (n *Node) ToMap() interface{} {
    if len(n.Children) < 1 {
        return "true"
    }

    yamlMap := make(map[string]interface{})

    for _, child := range n.Children {
        yamlMap[child.Name] = child.ToMap()
    }

    return yamlMap
}

此函数生成的映射可以由 gopkg.in/yaml.v2 编组到您想要的格式的 yaml 文件中。

这是在 Go Playground 中运行的代码,包括编组到 yaml

理论要掌握,实操不能落!以上关于《将通用映射转换为 YAML。 Go语言》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注golang学习网公众号吧!

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