Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to unmarshal a yaml array?

Tags:

yaml

go

I have next yaml, if I validate it in online yaml website, it said it's valid:

- {"foo": "1", "bar": "2"}

Then, I write a code to parse the value 1 and 2 from this yaml as next:

test.go:

package main
import "gopkg.in/yaml.v2"
import "fmt"

type Config struct {
    Foo string
    Bar string
}

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

func main() {
    //var data = `
    //  foobar:
    //  - foo: 1
    //    bar: 2
    //`
    var data = `
      - foo: 1
        bar: 2
    `

    source := []byte("foobar:" + data)
    var configs Configs
    err := yaml.Unmarshal(source, &configs)
    if err != nil {
        fmt.Println("error: %v", err)
    }
    fmt.Printf("--- configs:\n%v\n\n", configs)
    fmt.Println(configs.Cfgs[0].Foo)
    fmt.Println(configs.Cfgs[0].Bar)
}

It works ok as next:

shubuntu1@shubuntu1:~/20210810$ go run test.go
--- configs:
{[{1 2}]}

1
2

What's the problem?

You could see I made a workaround here as next to add special foobar key before the original yaml, then I could use type Configs struct to unmarshal it:

From

- foo: 1
  bar: 2

to

foobar:
- foo: 1
  bar: 2

So, if I don't use the workaround to add a prefix foobar:, how could I directly parse - {"foo": 1, "bar": 2}?

like image 570
atline Avatar asked Sep 11 '25 17:09

atline


1 Answers

Since your YAML data is an array, unmarshal it to an array of Config structure.

package main

import (
    "fmt"

    "gopkg.in/yaml.v2"
)

type Config struct {
    Foo string
    Bar string
}

func main() {
    var configs []Config

    var data = `
      - foo: 1
        bar: 2
    `

    err := yaml.Unmarshal([]byte(data), &configs)
    if err != nil {
        panic(err)
    }

    fmt.Println(configs)
}

Output:

[{1 2}]

Try on - Go Playground

like image 72
Kamol Hasan Avatar answered Sep 14 '25 19:09

Kamol Hasan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!