I am trying to parse a json-like string which looks like this.
"abc:9, bar:3"
What I would like to have at the end is a map[string]int
which looks like this:
map[string]int{"abc":9, "bar":3}
I have gotten as far as splitting it into a set of 'pairs', like so:
`["abc:9", "bar:3"]
I am struggling with how to get that structure into the final map[string]int
. I have tried ranging over the slice, but I am missing how to actually get it into the map.
val := "abc:9, bar:3"
lsd := make(map[string]int)
c := strings.Split(val, ",")
for k, v := range c {
lsd = v[k] // where I am struggling, I know this is wrong, but I can't seem to find the proper syntax and tools for this
}
Can anyone point me in the right direction to end up with the map[string]int I am looking for here?
This is a tiny bit cheesy but I was having trouble making fmt.Sscanf grok the pattern, so I am just splitting again. And you may have been missing strconv
- strconv.Atoi
is a quick converter.
package main
import (
"fmt"
"strconv"
"strings"
)
func main() {
lsd := make(map[string]int)
toParse := "abc:5, foo:5"
parts := strings.Split(toParse, ", ")
for _, p := range parts {
results := strings.SplitN(p, ":", 2)
val, err := strconv.Atoi(results[1])
if err != nil {
panic(err) //probably want to do somethig better
}
lsd[results[0]] = val
}
fmt.Printf("%#v", lsd)
}
map[string]int{"abc":5, "foo":5}