Go Yaml Interpretation Example

1.4k Views Asked by At

This Go Yaml Interpretation Example, https://gist.github.com/suntong001/74c85d15b19ef4b14b0e, can unmarshal a simple YAML like this:

foo: 1
bar:
  - one
  - two

Now I want to interpretation an array of the exact same data structure, what's the correct way to do?

Below is my code so far, and it is not working as expected. Please help.

package main

import (
    "fmt"
    "log"

    "gopkg.in/yaml.v2"
)

type Config struct {
    Foo string
    Bar []string
}

type Configs struct {
    Cfgs []Config
}

var data = `
- foo: 1
  bar:
    - one
    - two
    - three
- foo: 2
  bar:
    - one1
    - two2
    - three3
`

func main() {

  var config Configs

    /*
       filename := os.Args[1]
       source, err := ioutil.ReadFile(filename)
       if err != nil {
           panic(err)
       }
    */

    source := []byte(data)

    err := yaml.Unmarshal(source, &config)
    if err != nil {
        log.Fatalf("error: %v", err)
    }

    //fmt.Printf("Value: %#v\n", config.Bar[0])

    fmt.Printf("--- config:\n%v\n\n", config)
}

UPDATE:

To make it work, Jfly pointed out, simply replace my var config Configs with var config []Config, and it does the trick. Now I think if change my data definition to the following, my above code would work.

foobars:
 - foo: 1
   bar:
    - one
    - two
    - three

 - foo: 2
   bar:
    - one1
    - two2
    - three3

Nops, it doesn't. Please help.

1

There are 1 best solutions below

5
On BEST ANSWER

The contents of the example yaml file are sequence of objects, so do it like this:

package main

import (
    "fmt"
    "log"

    "gopkg.in/yaml.v2"
)

type Config struct {
    Foo string
    Bar []string
}

var data = `
- foo: 1
  bar:
    - one
    - two
    - three
- foo: 2
  bar:
    - one1
    - two2
    - three3
`

func main() {

    var config []Config

    /*
       filename := os.Args[1]
       source, err := ioutil.ReadFile(filename)
       if err != nil {
           panic(err)
       }
    */

    source := []byte(data)

    err := yaml.Unmarshal(source, &config)
    if err != nil {
        log.Fatalf("error: %v", err)
    }

    //fmt.Printf("Value: %#v\n", config.Bar[0])

    fmt.Printf("--- config:\n%v\n\n", config)
}

As to your updated question, your code almost works, just give a hint to the yaml parser like this:

type Configs struct {
    Cfgs []Config `foobars`
}