将特定格式的字符串转换为map[string]string。

huangapple go评论78阅读模式
英文:

Convert specific formatted string to map[string]string

问题

我有一些上游数据管道,其中有一个字符串类型的变量,其值如下:

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

我该如何将其转换为map[string]string,并获取特定键的值?

英文:

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.

答案1

得分: 1

这是一个简单的字符串解析问题。在这里使用strings.Split()函数非常有用。

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)
}

输出结果:

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

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]

huangapple
  • 本文由 发表于 2022年4月14日 23:19:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/71873963.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定