在Golang中解析YAML文件的问题

huangapple go评论169阅读模式
英文:

Issues in parsing yaml file in golang

问题

我正在寻找解析简单的 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)
}

我得到了下面的空输出:

Config [{ } { }]

Playground -> https://play.golang.org/p/LANMpq_zPP9

英文:

I am looking for unmarshaling simple yaml but something is not right. Have spent enough time already. Any help please?

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)
}

I am getting below empty o/p

Config {[{ } { }]}

Playground -> https://play.golang.org/p/LANMpq_zPP9

答案1

得分: 1

你必须导出结构体中的字段。根据 API 文档的说明:

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

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

将你的 Target 结构体修改为:

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

应该可以正常工作。

试一下:https://play.golang.org/p/ZD7Jrv0QBdn

英文:

You have to export the fields in your struct. As stated in the api-documentation:
> Struct fields are only unmarshalled if they are exported (have an upper case first letter), and are unmarshalled using the field name lowercased as the default key.

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

Changing your Target-struct to:

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

should work.

Try it: https://play.golang.org/p/ZD7Jrv0QBdn

huangapple
  • 本文由 发表于 2021年6月5日 05:42:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/67844296.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定