Skip to content

Instantly share code, notes, and snippets.

@peschmae
Forked from jghiloni/yaml-nest.go
Last active March 11, 2024 21:09
Show Gist options
  • Save peschmae/20527cc1c4d7d45f2fd278d8b51e792c to your computer and use it in GitHub Desktop.
Save peschmae/20527cc1c4d7d45f2fd278d8b51e792c to your computer and use it in GitHub Desktop.
Convert a string 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() {
data := []byte("tool.argocd.blub: true\ntool.argocd.bla: false")
initialData := new(map[interface{}]interface{})
decoder := yaml.NewDecoder(bytes.NewReader(data))
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