-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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