duandange7480 2016-10-21 03:34
浏览 436
已采纳

转:反序列化数组字符串

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.

  • 写回答

1条回答 默认 最新

  • dongshangan2074 2016-10-21 03: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, 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"  ]  `
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部