dongshuo6185 2017-01-04 09:49
浏览 597
已采纳

如何将utf8字符串转换为[] byte?

I want to unmarshal a string that contains JSON, however the Unmarshal function takes a []byte as input.

How can I convert my UTF8 string to []byte?

  • 写回答

2条回答 默认 最新

  • douerqu2319 2017-01-04 10:00
    关注

    This question is a possible duplicate of How to assign string to bytes array, but still answering it as there is a better, alternative solution:

    Converting from string to []byte is allowed by the spec, using a simple conversion:

    Conversions to and from a string type

    [...]

    1. Converting a value of a string type to a slice of bytes type yields a slice whose successive elements are the bytes of the string.

    So you can simply do:

    s := "some text"
    b := []byte(s) // b is of type []byte
    

    However, the string => []byte conversion makes a copy of the string content (it has to, as strings are immutable while []byte values are not), and in case of large strings it's not efficient. Instead, you can create an io.Reader using strings.NewReader() which will read from the passed string without making a copy of it. And you can pass this io.Reader to json.NewDecoder() and unmarshal using the Decoder.Decode() method:

    s := `{"somekey":"somevalue"}`
    
    var result interface{}
    err := json.NewDecoder(strings.NewReader(s)).Decode(&result)
    fmt.Println(result, err)
    

    Output (try it on the Go Playground):

    map[somekey:somevalue] <nil>
    

    Note: calling strings.NewReader() and json.NewDecoder() does have some overhead, so if you're working with small JSON texts, you can safely convert it to []byte and use json.Unmarshal(), it won't be slower:

    s := `{"somekey":"somevalue"}`
    
    var result interface{}
    err := json.Unmarshal([]byte(s), &result)
    fmt.Println(result, err)
    

    Output is the same. Try this on the Go Playground.

    Note: if you're getting your JSON input string by reading some io.Reader (e.g. a file or a network connection), you can directly pass that io.Reader to json.NewDecoder(), without having to read the content from it first.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥200 uniapp长期运行卡死问题解决
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?
  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败