如何使用 golang 解析其中的列表 yaml?

How to parse a yaml of lists in it using golang?

示例 yaml 文件 final-result.yml:

- category: 1
  rules:
  - name: a
    results:
    - asset: b
      advice: c

- category: 2
  rules:
  - name: d
    results:
    - asset: e
      advice: f

我尝试对包 gopkg.in/yaml.v2 进行解组:

package main

import (
    "io/ioutil"
    "log"

    "gopkg.in/yaml.v2"
)

type FinalResult struct {
    category string      `yaml:"category"`
    rules    []RulesItem `yaml:"rules,flow"`
}

type RulesItem struct {
    name    string        `yaml:"name"`
    results []ResultsItem `yaml:"results,flow"`
}

type ResultsItem struct {
    asset  string `yaml:"asset"`
    advice string `yaml:"advice"`
}

func main() {
    var result []FinalResult

    content, err := ioutil.ReadFile("final-result.yml")
    if err != nil {
        log.Fatal(err.Error())
        return
    }
    err = yaml.Unmarshal(content, &result)
    if err != nil {
        log.Fatal("Failed to parse file ", err)
    }

    log.Println(result)
}

但它给出了一个空结果:

[{ []} { []}]

根据 documentation,您应该使结构字段 public 以便解组正确填充数据。:

Struct fields are only unmarshalled if they are exported (have an upper case first letter)

按如下方式更改类型定义后,您的代码按预期工作:

type FinalResult struct {
    Category string      `yaml:"category"`
    Rules    []RulesItem `yaml:"rules,flow"`
}

type RulesItem struct {
    Name    string        `yaml:"name"`
    Results []ResultsItem `yaml:"results,flow"`
}

type ResultsItem struct {
    Asset  string `yaml:"asset"`
    Advice string `yaml:"advice"`
}