更新时间:2022-11-14 16:57:01
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:
使用简单的转化:
与字符串类型之间的转换
[...]
所以您可以简单地做:
s := "some text"
b := []byte(s) // b is of type []byte
但是, string =>[] byte
转换会生成字符串内容的副本(必须复制,因为 string
是不可变的,而 [] byte
值不是不可更改的),并且在 string
较大的情况下,效率不高.相反,您可以使用 io.Reader
href ="https://golang.org/pkg/strings/#NewReader" rel ="nofollow noreferrer"> strings.NewReader()
将从传递的中读取字符串
而不复制它.并且您可以将此 io.Reader
传递给 json.NewDecoder()
并使用 Decoder进行解组.Decode()
方法:
However, the string => []byte
conversion makes a copy of the string content (it has to, as string
s are immutable while []byte
values are not), and in case of large string
s 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)
输出(在游乐场上尝试):
map[somekey:somevalue] <nil>
注意:调用 strings.NewReader()
和 json.NewDecoder()
确实有一些开销,因此,如果您使用的是小型JSON文本,则可以放心将其转换为 [] byte
并使用 json.Unmarshal()
,它不会变慢:
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.
注意:如果通过读取一些 io.Reader
(例如文件或网络连接)来获取JSON输入 string
,则可以直接传递 io.Reader
转换为 json.NewDecoder()
,而无需先从中读取内容.
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.