Convert specific formatted string to map[string]string

Issue

I have some upstream data pipeline and I have string type variable with value as below

map[admin_username:deploy image_name:rhel_lvm84-gen2 vm_size:Standard_DS4_v2]

How can I convert it to map[string]string and get the value of specific key.

Solution

This is a simple matter of parsing the string. Using strings.Split() is useful here.

func main() {
    ret := make(map[string]string)
    s := "map[admin_username:deploy image_name:rhel_lvm84-gen2 vm_size:Standard_DS4_v2]"
    rawMap := s[strings.Index(s, "map[")+4:strings.LastIndex(s,"]")]
    pairs := strings.Split(rawMap, " ")
    for _, pair := range pairs {
        kvp := strings.SplitN(pair, ":", 2)
        if len(kvp) != 2 {
            fmt.Printf("Bad key-value pair, ignoring...")
            continue
        }
        ret[kvp[0]] = kvp[1]
    }
    fmt.Printf("Here is the result len=%d :%+v", len(ret), ret)
}

Output:

Here is the result len=3 :map[admin_username:deploy image_name:rhel_lvm84-gen2 vm_size:Standard_DS4_v2]

Answered By – Toivo Lainevool

Answer Checked By – Jay B. (GoLangFix Admin)

Leave a Reply

Your email address will not be published.