-2

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.

2
  • 1
    Who is sending you a map in this textual format? Can they not use a more appropriate encoding?
    – jub0bs
    Apr 14, 2022 at 15:33
  • What exactly is the format? We can make some guesses from this example, but that does not provide a strict syntax for parsing.
    – JimB
    Apr 14, 2022 at 16:19

1 Answer 1

1

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]

Not the answer you're looking for? Browse other questions tagged or ask your own question.