Go语言 如何从我的yaml文件访问'map[string]interface {}'数据

2ekbmq32  于 2022-12-07  发布在  Go
关注(0)|答案(1)|浏览(126)

我有一个yaml文件,我试图读入和循环提取一些数据。
My yaml示例

---
THE/NAME/DOESNT/MATTER:
  TEST_NAME: THIS/IS/WHAT/IS/DISPLAYS/ON/THE/HTML
  RUN_PATH: example/testfiles/release
  SOMETHING_ELSE: [1,2,3]
ANOTHER/PATH/LIKE/STRING:
  TEST_NAME: USED/FOR/THE/HTML
  RUN_PATH: example/testfiles/foo

我的代码

package main
import (
    "fmt"
    "os"
    "io/ioutil"

    "gopkg.in/yaml.v3"
)

func main() {
    reportYAML := os.Args[1]
    // userDictionary := os.Args[2]

    yfile, err := ioutil.ReadFile(reportYAML)
    if err != nil {
        fmt.Printf("ERROR: Unable to open yaml file : %s\n", err)
    }
    data := make(map[interface{}]interface{})
    error := yaml.Unmarshal([]byte(yfile), &data)
    if error != nil {
        fmt.Printf("ERROR: Unable to read yaml file : %s\n", err)
    }
    for _, value := range data {
        fmt.Printf("%T\n", value)
    }
    
}

yaml将以类似的模式重复,我正在尝试提取TEST_NAME和RUN_PATH。使用%T的Printf将提供map[string]interface {}和%s map[RUN_PATH:example/testfiles/release SOMETHING_ELSE:[%!s(int=1) %!s(int=2) %!s(int=3)] TEST_NAME:THIS/IS/WHAT/IS/DISPLAYS/ON/THE/HTML]
我一直在尝试value["TESTNAME"]value.(string)["TESTNAME"]value["TESTNAME"].(string)和其他一些变体,但它们都给予我错误。
我知道这是一个简单的问题,但我对GO的经验很少,不能从以前的类似stackoverflow的帖子中解决这个问题
附加上下文:每个yaml顶层键将包含多个键:值对,但我只对TEST_NAME和RUN_PATH感兴趣

ufj5ltwl

ufj5ltwl1#

如果您只关心几个特定的键,只需创建一个数据结构来公开这些值:

package main

import (
    "fmt"
    "io/ioutil"
    "os"

    "gopkg.in/yaml.v3"
)

type (
    Entry struct {
        TestName string `yaml:"TEST_NAME"`
        RunPath  string `yaml:"RUN_PATH"`
    }
)

func main() {
    reportYAML := os.Args[1]
    // userDictionary := os.Args[2]

    yfile, err := ioutil.ReadFile(reportYAML)
    if err != nil {
        fmt.Printf("ERROR: Unable to open yaml file : %s\n", err)
    }
    data := make(map[string]Entry)
    error := yaml.Unmarshal([]byte(yfile), &data)
    if error != nil {
        fmt.Printf("ERROR: Unable to read yaml file : %s\n", err)
    }
    for _, value := range data {
        fmt.Printf("test_name: %s\n", value.TestName)
        fmt.Printf("run_path: %s\n", value.RunPath)
    }
}

对示例数据运行上述代码将生成:

test_name: THIS/IS/WHAT/IS/DISPLAYS/ON/THE/HTML
run_path: example/testfiles/release
test_name: USED/FOR/THE/HTML
run_path: example/testfiles/foo

相关问题