dragam0217 2014-10-13 01:50
浏览 367
已采纳

如何在Go中将unicode字节数组转换为普通字符串

I'm getting the byte array from unix socket and try to print as a string. I just string(bytes) and get the following string.

{\"Created\":1410263175,\"Id\":\"f4e36130333537c3725e212f78d603742cf3da4b738272f7232338b0d61fa4fb\",\"ParentId\":\"a8a806a76e3e620a6f2172e401847beb4535b072cf7e60d31e91becc3986827e\",\"RepoTags\":[\"\\u003cnone\\u003e:\\u003cnone\\u003e\"],\"Size\":0,\"VirtualSize\":1260903901}
,

How can I remove the escape char \ and convert unicode char \u003 into normal string?

  • 写回答

1条回答 默认 最新

  • douyou1857 2014-10-13 02:21
    关注

    This looks like a JSON string with \u escapes per the JSON specification. The JSON decoder will take care of unescaping the strings.

    The code:

    s := "{\"Created\":1410263175,\"Id\":\"f4e36130333537c3725e212f78d603742cf3da4b738272f7232338b0d61fa4fb\",\"ParentId\":\"a8a806a76e3e620a6f2172e401847beb4535b072cf7e60d31e91becc3986827e\",\"RepoTags\":[\"\\u003cnone\\u003e:\\u003cnone\\u003e\"],\"Size\":0,\"VirtualSize\":1260903901}
    "
    var m map[string]interface{}
    if err := json.Unmarshal([]byte(s), &m); err != nil {
        log.Fatal(err)
    }
    fmt.Printf("%#v", m)
    

    prints the following (minus the white space that I added for readability):

    map[string]interface {}{
         "Created":1.410263175e+09, 
         "Id":"f4e36130333537c3725e212f78d603742cf3da4b738272f7232338b0d61fa4fb",
         "ParentId":"a8a806a76e3e620a6f2172e401847beb4535b072cf7e60d31e91becc3986827e", 
         "RepoTags":[]interface {}{"<none>:<none>"}, 
         "Size":0, 
         "VirtualSize":1.260903901e+09}
    

    <kbd>playground</kbd>

    The \u escape is not created when converting bytes to a string in Go. It's part of the byte sequence generated by a JSON encoder. The string conversion operator string(byteSlice) converts these bytes to a string as is.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了