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

How to convert utf8 string to []byte?

我想解组一个包含 JSON 的 string, 但是 Unmarshal 函数将 []byte 作为输入。

如何将我的 UTF8 string 转换为 []byte

只需在字符串上使用 []byte(s)。例如:

package main

import (
    "encoding/json"
    "fmt"
)

func main() {
    s := `{"test":"ok"}`
    var data map[string]interface{}
    if err := json.Unmarshal([]byte(s), &data); err != nil {
        panic(err)
    }
    fmt.Printf("json data: %v", data)
}

去游乐场看看here

这个问题可能与 How to assign string to bytes array 重复,但仍然回答它,因为有更好的替代解决方案:

规范允许从 string 转换为 []byte,使用简单的 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.

所以你可以简单地做:

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

但是,string => []byte 转换会复制字符串内容(它必须这样做,因为 string 是不可变的,而 []byte 值不是),如果大 strings 效率不高。相反,您可以创建一个 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() 方法:

s := `{"somekey":"somevalue"}`

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

输出(在 Go Playground 上尝试):

map[somekey:somevalue] <nil>

注意:调用 strings.NewReader()json.NewDecoder() 确实有一些开销,所以如果您使用的是 JSON 小文本,您可以安全地将其转换为 []byte并使用json.Unmarshal(),它不会更慢:

s := `{"somekey":"somevalue"}`

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

输出相同。在 Go Playground.

上试试这个

注意:如果您通过读取一些 io.Reader(例如文件或网络连接)获得 JSON 输入 string,您可以直接传递 io.Readerjson.NewDecoder(),而不必先从中读取内容。