【问题标题】:Parsing a yaml object in Go which contains a struct在 Go 中解析包含结构的 yaml 对象
【发布时间】:2017-03-14 13:04:12
【问题描述】:

我有以下 yaml:

segmentforward: ""
segmentbackward: ""
listforward: ""
promptready: "➜"

enabledhooks: ["alert"]

enabledsegments: ["host", "path", "python_env", "aws", "git", "filler", "command", "timestamp", "newline", "prompt_ready"]

hostsegment: { fgcolor: 250, bgcolor: 238 }
pathsegment: { fgcolor: 15, bgcolor: 31 }
pythonenvsegment: { fgcolor: 15, bgcolor: 22 }
awssegment: { fgcolor: 172, bgcolor: 238 }
gitsegment: { fgcolor: 238, bgcolor: 148 }
fillersegment: { fgcolor: 251, bgcolor: 251 }
commandsegment: { fgcolor: 238, bgcolor: 250 }
timestampsegment: { fgcolor: 250, bgcolor: 238 }
promptreadysegment: { fgcolor: 238, bgcolor: 251 }

我正在尝试使用以下 go 代码解析此 yaml:

package config

import (
    "gopkg.in/yaml.v2"
    "io/ioutil"
)

type Config struct {
    SegmentForward string
    SegmentBackward string
    ListForward string
    PromptReady string
    EnabledHooks []string
    EnabledSegments []string
    HostSegment struct {
      FgColor int
      BgColor int
    }
}

func LoadConfig(path string) (config Config) {

    data, err := ioutil.ReadFile(path)
    if err != nil {
      panic(err)
    }

    err = yaml.Unmarshal(data, &config)
    if err != nil {
      panic(err)
    }

    return config
}

但这给了我错误:

panic: yaml: unmarshal errors:
  line 18: cannot unmarshal !!map into string

goroutine 1 [running]:
panic(0x3364c0, 0xc42014a9c0)
    /usr/local/Cellar/go/1.7.4/libexec/src/runtime/panic.go:500 +0x1a1
github.com/brujoand/sbp/config.LoadConfig(0x3b7138, 0x23, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, ...)
    /opt/go/src/github.com/brujoand/sbp/config/config.go:30 +0x12d
main.main()
    /opt/go/src/github.com/brujoand/sbp/main.go:18 +0x50

我在这里想要的是能够直接引用这些段而无需查找地图。然后在每个段内都有相同类型的字段。我知道我在 Yaml 中的命名不是很好(对此感到抱歉),但现在我正试图了解如何以简单的方式访问这些字段。

【问题讨论】:

  • play.golang.org/p/NX5qQhHZFu - 这对我有用。确保您的 YAML 格式正确。
  • 谢谢!我复制了你的 yaml 版本。现在它可以工作了。我试图区分它们,但找不到任何区别。很奇怪,但问题解决了。

标签: go yaml


【解决方案1】:

这个 yaml 可以完美地解组(因为你不想使用地图):

type Config struct {
    SegmentForward  string
    SegmentBackward string
    ListForward     string
    PromptReady     string
    EnabledHooks    []string
    EnabledSegments []string

    HostSegment, PathSegment, PythonEnvSegment, AWSSegment, GitSegment  segment
    FillerSegment, CommandSegment, TimestampSegment, PromptReadySegment segment
}

type segment struct {
    FgColor int
    BgColor int
}

【讨论】:

    猜你喜欢
    • 2018-05-24
    • 1970-01-01
    • 1970-01-01
    • 2019-01-20
    • 2019-01-17
    • 1970-01-01
    • 2017-04-08
    • 1970-01-01
    • 2019-12-07
    相关资源
    最近更新 更多