Skip to content
This repository was archived by the owner on Apr 1, 2025. It is now read-only.
This repository was archived by the owner on Apr 1, 2025. It is now read-only.

Unmarshal slice via interface #282

@akerl

Description

@akerl

I'm running into what feels like a weird issue. Brief background: I have a tool that loads config info via YAML and hands the config to a variety of plugins, whose YAML layouts differ. As such, I find myself using map[string]interface{} in the YAML Unmarshal-ing. But when one of the map values is a slice, it appears to get mangled and refuse to type convert back.

Here's a slimmed down example:

package main

import (
    "fmt"

    "gopkg.in/yaml.v2"
)

var data = `
data:
- foo
- bar
- baz
`

type doc struct {
    Data interface{}
}

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

    data, ok := d.Data.([]string)
    if !ok {
        fmt.Println("Things are not ok")
        return
    }

    fmt.Printf("%+v\n", data)
    fmt.Printf("%+v\n", data[0])
}

Which returns the following:

❯ go run main.go
Things are not ok

Am I missing some adjustment when Unmarshalling that's causing my YAML list to be mangled?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions