I have a string in Go ('["a","b","50"]') which I need to convert into a []string type.
To me, that is basically evaluating the string, but I have no idea how to do this in Go (I come from Python). I did search the strconv package documentation, but did not really find anything that worked.
1 Answer
You could use json package for that, as your string is clearly a JSON array:
import (
"encoding/json"
"fmt"
)
func main() {
str := `["a","b","50"]`
slice := []string{}
err := json.Unmarshal([]byte(str), &slice)
if err == nil {
fmt.Printf("%v\n", slice)
}
}
An alternative would be to use strings.Split(str, ","), but then you'll have to strip those [] and ""
evalis a very dangerous thing in general. The Python version has been revised a lot over time and in Python3 you can restrict it to reduce this danger, but if you don't carefully vet input and just blindly feed it to some execution engine, you get xkcd.com/327 😀 If your string is JSON, as it seems to be, see Alexey Soshin's answer.