Skip to content

Instantly share code, notes, and snippets.

@termie
Last active September 20, 2017 18:13
Show Gist options
  • Select an option

  • Save termie/700ab185b4393ec43b22 to your computer and use it in GitHub Desktop.

Select an option

Save termie/700ab185b4393ec43b22 to your computer and use it in GitHub Desktop.
golang: yaml and strings and interfaces oh my
Dear internet, I have a stupid data structure transformation problem
(and probably an "i don't understand go interfaces" problem)
data = {'build': {'steps': [{'some_name': {'data1': 'foo', 'data2': 'bar'}},
{'another_name': {'data3': 'baz', 'data4': 'qux'}}
]
}
}
(due to the shape of the yaml file, the "steps" key is a bunch of single-item hashes)
this is parsed from a yaml file using "gopkg.in/yaml.v1", so each
section is a map[interface{}]interface{}
(docs for that packaged: https://github.com/go-yaml/yaml )
I am trying to get a list in the form of:
[(some_name, {data1: ...},
(another_name, {data3: ...}
]
specifically a bunch of (string, map[string]string) pairs
In python I would do:
[x.popitem() for x in data['build']['steps']]
In golang I am doing this and I feel like an idiot, what am I doing wrong?:
m := make(map[string]interface{})
// doesn't seem to matter if I use make(map[interface{}]interface{}) instead
err = yaml.Unmarshal(file, &m)
build := m["build"].(map[interface]interface{})
steps := build["steps"].([]interface{})
for _, v := range steps {
var stepId string
stepData := make(map[string]string)
// There is only one key in this map but can't figure out how to pop in golang
for id, data := range v.(map[interface{}]interface{}) {
stepId = id.(string)
for prop, value := range data.(map[interface{}]interface{}) {
stepData[prop.(string)] = value.(string)
}
}
fmt.Println(stepId, stepData)
}
Is there a way not to type assert that many times?
A way to do the equiv of python's dict.popitem()?
It works as is but I feel like there has to be a better way
@tony
Copy link

tony commented Mar 7, 2016

Did you ever figure this out? This problem happens even more crazily yaml.

@arehmandev
Copy link

Why not try use viper's extract sub tree function? https://github.com/spf13/viper

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment