登录
首页 >  Golang >  Go问答

如何解组 YAML v3 并具有对节点的完全访问权限

来源:stackoverflow

时间:2024-04-13 09:51:33 208浏览 收藏

积累知识,胜过积蓄金银!毕竟在Golang开发的过程中,会遇到各种各样的问题,往往都是一些细节知识点还没有掌握好而导致的,因此基础知识点的积累是很重要的。下面本文《如何解组 YAML v3 并具有对节点的完全访问权限》,就带大家讲解一下知识点,若是你对本文感兴趣,或者是想搞懂其中某个知识点,就请你继续往下看吧~

问题内容

我正在尝试学习使用 yaml v3 解组来完全访问复杂嵌入式结构中的节点。

公告帖子解释了如何使用yaml.node,但没有给出严肃的示例。而且文档也没有显示如何使用 node.js。主要目的似乎是在 yaml 文件中很好地保存注释。

例如,使用公告文章的扩展,我有

package main

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

func main() {

    type Person struct {
        Name    string
        Address yaml.Node
    }

    data := `
name: John Doe
address: 
    street: 123 E 3rd St # street is like an avenue
    city: Denver  # A city might be a town as well
    state: CO  # A state might be a province or administrative unit
    zip: 81526 # zip might be "postal_code"
`

    var person Person
    err := yaml.Unmarshal([]byte(data), &person)
    if (err != nil) {
        fmt.Printf("Failed to unmarshall: %v", err)
        os.Exit(1)
    }
    fmt.Printf("Marshalled person=%v", person)

}

但是,如果我尝试使用地址项,我会发现它们每个都列为节点内的内容数组;那里没有实际有用的信息。评论就在那里,但不清楚它们与什么相关。

修改现有 yaml 文件并添加新数据和注释也处理相同的领域,但不显示在解组到结构后导航结构。

解组后如何导航“地址”节点,并再次保留编组注释?


解决方案


因此 node 结构体具有三个字段,它们是:

// headcomment holds any comments in the lines preceding the node and
// not separated by an empty line.
headcomment string

// linecomment holds any comments at the end of the line where the node is in.
linecomment string

// footcomment holds any comments following the node and before empty lines.
footcomment string

此 ^ 取自文档 here。对上面的示例稍作补充:

package main

import (
    "fmt"
    "os"

    "gopkg.in/yaml.v3"
)

func main() {
    type person struct {
        name    yaml.node
        address yaml.node
    }

    data := `
name: john doe
#comment here
address: 
    street: 123 e 3rd st
    city: denver
    state: co
    zip: 81526
`

    var person person
    err := yaml.unmarshal([]byte(data), &person)
    if err != nil {
        fmt.printf("failed to unmarshall: %v", err)
        os.exit(1)
    }
    address := &yaml.node{}

    decerr := person.address.decode(address)
    if decerr != nil {
        fmt.printf("failed to decode: %v", decerr)
        os.exit(1)
    }
    fmt.printf("%v", address.headcomment)
}

就我们而言

#comment here
address: 
    street: 123 E 3rd St
    city: Denver
    state: CO
    zip: 81526

可以称为node,并且可以从node结构中的字段访问它的注释。但尽管我能够访问文档中指出的其他字段,但我仍然无法获得节点上方的注释。

理论要掌握,实操不能落!以上关于《如何解组 YAML v3 并具有对节点的完全访问权限》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注golang学习网公众号吧!

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