I have a string as: - ["a","b","c"]
. How to parse / convert it into a Go array? I can do string parsing but is there any out of the box function in Go for the same.
How about using json.Unmarshal()
?
s := `["a","b","c"]`
var arr []string
if err := json.Unmarshal([]byte(s), &arr); err != nil {
fmt.Println("Error:", err)
}
fmt.Printf("%q", arr)
Output (try it on the Go Playground):
["a" "b" "c"]
But know that package json
does a lot of reflection kung-fu under the hood, it's faster if you write the parsing yourself. On the other hand, package json
will also handle random white-spaces in the input – even newline characters and Unicode sequences, like this one (it's equivalent to ["a","b","c"]
):
s := `[ "a" , "b"
,"\u0063" ] `