如何将UTF-8字符串转换为[]byte类型?

huangapple go评论89阅读模式
英文:

How to convert utf8 string to []byte?

问题

你可以使用[]byte函数将UTF8字符串转换为字节数组。在Go语言中,字符串是由字节数组组成的,因此可以直接将字符串转换为字节数组。以下是一个示例代码:

package main

import (
	"encoding/json"
	"fmt"
)

func main() {
	jsonString := `{"name":"John","age":30,"city":"New York"}`

	// 将UTF8字符串转换为字节数组
	byteArray := []byte(jsonString)

	// 使用Unmarshal函数解析JSON
	var data map[string]interface{}
	err := json.Unmarshal(byteArray, &data)
	if err != nil {
		fmt.Println("解析JSON时出错:", err)
		return
	}

	fmt.Println(data)
}

在上面的示例中,我们首先将UTF8字符串jsonString转换为字节数组byteArray,然后使用Unmarshal函数解析JSON数据。请注意,Unmarshal函数的第二个参数是一个指向目标数据结构的指针,这里我们使用了map[string]interface{}来解析JSON对象。

希望这可以帮助到你!如果你有任何其他问题,请随时问我。

英文:

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?

答案1

得分: 17

这个问题可能是https://stackoverflow.com/questions/8032170/how-to-assign-string-to-bytes-array的重复问题,但还是回答一下,因为有一个更好的替代解决方案:

根据规范,可以通过简单的转换string转换为[]byte

字符串类型的转换

[...]

  1. 将字符串类型的值转换为字节切片类型会产生一个切片,其连续的元素是字符串的字节。

所以你可以简单地这样做:

s := "some text"
b := []byte(s) // b 的类型是 []byte

然而,string => []byte 的转换会复制字符串的内容(因为 string 是不可变的,而 []byte 值不是),对于大型字符串来说效率不高。相反,你可以使用 strings.NewReader() 创建一个 io.Reader,它将从传递的 string 中读取而不进行复制。然后,你可以将这个 io.Reader 传递给 json.NewDecoder() 并使用 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.Reader 直接传递给 json.NewDecoder(),而不需要先从中读取内容。

英文:

This question is a possible duplicate of https://stackoverflow.com/questions/8032170/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
>
> [...]
>
> 4. 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 := &quot;some text&quot;
b := []byte(s) // b is of type []byte

However, the string =&gt; []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 := `{&quot;somekey&quot;:&quot;somevalue&quot;}`

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

Output (try it on the Go Playground):

map[somekey:somevalue] &lt;nil&gt;

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 := `{&quot;somekey&quot;:&quot;somevalue&quot;}`

var result interface{}
err := json.Unmarshal([]byte(s), &amp;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.

答案2

得分: 1

只需在字符串上使用[]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)
}

在playground上查看这里

英文:

just use []byte(s) on the string. for example:

package main

import (
	&quot;encoding/json&quot;
	&quot;fmt&quot;
)

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

check it out on the playground here.

huangapple
  • 本文由 发表于 2017年1月4日 17:49:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/41460750.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定