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.
转:反序列化数组字符串
- 写回答
- 好问题 0 提建议
- 追加酬金
- 关注问题
- 邀请回答
-
1条回答 默认 最新
- dongshangan2074 2016-10-21 11:41关注
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, packagejson
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" ] `
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报