Skip to content

Instantly share code, notes, and snippets.

@jghiloni
Created June 7, 2018 03:00
Show Gist options
  • Save jghiloni/37b58dd23e12bc2cbf9961315f65c54e to your computer and use it in GitHub Desktop.
Save jghiloni/37b58dd23e12bc2cbf9961315f65c54e to your computer and use it in GitHub Desktop.
Convert a flat yaml file with property names that have dots in them to a nested structure
package main
import (
"log"
"os"
"strings"
"gopkg.in/yaml.v2"
)
func nestProperties(originalData *map[interface{}]interface{}, prefix string) map[interface{}]interface{} {
interiorProps := make(map[string]bool)
retVal := make(map[interface{}]interface{})
for keyIntf := range *originalData {
key, _ := keyIntf.(string)
if prefix != "" && !strings.HasPrefix(key, prefix) {
continue
}
key = strings.TrimPrefix(key, prefix)
if strings.Contains(key, ".") {
interiorNode := strings.SplitN(key, ".", 2)[0]
interiorProps[interiorNode] = true
} else {
retVal[key] = (*originalData)[prefix+key]
}
}
for key := range interiorProps {
retVal[key] = nestProperties(originalData, prefix+key+".")
}
return retVal
}
func main() {
initialData := new(map[interface{}]interface{})
decoder := yaml.NewDecoder(os.Stdin)
if err := decoder.Decode(initialData); err != nil {
log.Fatal(err)
}
nestedData := nestProperties(initialData, "")
encoder := yaml.NewEncoder(os.Stdout)
if err := encoder.Encode(nestedData); err != nil {
log.Fatal(err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment