英文:
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]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论