Mid*_*rse 0 string json type-conversion go slice
我想解组string包含JSON的内容,但是该Unmarshal函数需要[]byte输入.
如何将我的UTF8转换string为[]byte?
icz*_*cza 10
这个问题可能与如何将字符串分配给字节数组有关,但仍然可以回答它,因为有一个更好的替代解决方案:
从转换string到[]byte由该规范允许的,使用一个简单的转换:
转换为字符串类型的转换
[...]
- 将字符串类型的值转换为字节切片类型会生成一个切片,其连续元素是字符串的字节.
所以你可以简单地做:
s := "some text"
b := []byte(s) // b is of type []byte
Run Code Online (Sandbox Code Playgroud)
但是,string => []byte转换会生成字符串内容的副本(它必须是,因为strings是不可变的而[]byte值不是),并且在大strings的情况下它不是有效的.相反,您可以创建一个io.Reader使用strings.NewReader(),它将从传递中读取string而不复制它.你可以使用以下方法将其传递io.Reader给json.NewDecoder()unmarshal Decoder.Decode():
s := `{"somekey":"somevalue"}`
var result interface{}
err := json.NewDecoder(strings.NewReader(s)).Decode(&result)
fmt.Println(result, err)
Run Code Online (Sandbox Code Playgroud)
输出(在Go Playground上试试):
map[somekey:somevalue] <nil>
Run Code Online (Sandbox Code Playgroud)
注意:调用strings.NewReader()并json.NewDecoder()确实有一些开销,所以如果你正在使用小JSON文本,你可以安全地将其转换为[]byte并使用json.Unmarshal(),它不会更慢:
s := `{"somekey":"somevalue"}`
var result interface{}
err := json.Unmarshal([]byte(s), &result)
fmt.Println(result, err)
Run Code Online (Sandbox Code Playgroud)
输出是一样的.在Go Playground尝试这个.
注意:如果您string通过阅读某些内容io.Reader(例如文件或网络连接)获取JSON输入,则可以直接将其传递io.Reader给json.NewDecoder(),而无需先从中读取内容.