【问题标题】:Issues in parsing yaml file in golanggolang解析yaml文件的问题
【发布时间】:2021-06-04 21:42:14
【问题描述】:

我正在寻找解组简单的 yaml,但有些地方不对劲。已经花了足够的时间。有什么帮助吗?

package main

import (
    "fmt"

    yaml "gopkg.in/yaml.v2"
)

func main() {

    raw := `
targets:
  - from: "http://localhost:8080/test1"
    timeout: "10s"
  - from: "http://localhost:8080/test2"
    timeout: "30s"
`
    type Target struct {
        from    string `yaml:"from"`
        timeout string `yaml:"timeout"`
    }
    type config struct {
        Targets []Target `yaml:"targets"`
    }

    cfg := config{}

    err := yaml.Unmarshal([]byte(raw), &cfg)
    if err != nil {
        fmt.Println(err)
    }

    fmt.Println("Config", cfg)
}

我低于空 o/p

Config {[{ } { }]}

游乐场 -> https://play.golang.org/p/LANMpq_zPP9

【问题讨论】:

  • 顺便说一句,如果 go 编译器在这种情况下给出一些警告会更容易。
  • 我认为您之所以投反对票,是因为这被认为是一个基本问题。我很感激你有一个游乐场链接并展示了你尝试过的东西。在我看来,这是一个合理的问题。
  • 这个“{YML,JSON unmarshaling doesn't work!”-在 SO 上每周出现 2 到 10 次问题,答案总是一样的:导出你的字段!也不是这里的文档不清楚,或者官方文档中的示例会使用未导出的字段。

标签: go yaml


【解决方案1】:

您必须导出结构中的字段。如 api 文档中所述:

结构字段只有在被导出(首字母大写)时才会被解组,并且使用小写的字段名称作为默认键来解组。

(https://github.com/go-yaml/yaml/blob/496545a6307b/yaml.go#L88)

将您的 Target-struct 更改为:

type Target struct {
    From    string `yaml:"from"`
    Timeout string `yaml:"timeout"`
}

应该可以。

试试看:https://play.golang.org/p/ZD7Jrv0QBdn

【讨论】:

  • 大声笑,是时候再次了解基础知识了:-(
猜你喜欢
  • 2018-06-04
  • 2017-04-30
  • 2018-12-21
  • 1970-01-01
  • 2018-10-04
  • 2023-03-31
  • 1970-01-01
  • 1970-01-01
  • 2014-11-05
相关资源
最近更新 更多