How to Efficiently Convert a UTF-8 String to []byte for JSON Unmarshalling in Go?

Linda Hamilton
Release: 2024-10-30 21:50:02
Original
360 people have browsed it

How to Efficiently Convert a UTF-8 String to []byte for JSON Unmarshalling in Go?

Converting UTF-8 Strings to []byte for JSON Unmarshalling

To unmarshal a JSON string in Go, we need to provide a []byte slice as input. If we only have a UTF-8 string, how can we convert it to []byte?

Simple Conversion and String to []byte Copy

The Go type system allows us to convert directly from a string to []byte using:

s := "some text"
b := []byte(s) // b is type []byte
Copy after login

However, this operation creates a copy of the string, which can be inefficient for large strings.

Efficient Conversion Using io.Reader

An alternative solution involves creating an io.Reader using strings.NewReader():

s := `{"somekey":"somevalue"}`
r := strings.NewReader(s)
Copy after login

This io.Reader can then be passed to json.NewDecoder() for unmarshalling without creating a string copy:

var result interface{}
err := json.NewDecoder(r).Decode(&result)
Copy after login

Overhead Considerations

Using strings.NewReader() and json.NewDecoder() has some overhead, so for small JSON strings, converting to []byte directly may be more efficient:

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

Direct io.Reader Input

If the JSON string input is available as an io.Reader (e.g., a file or network connection), it can be passed directly to json.NewDecoder():

var result interface{}
err := json.NewDecoder(myReader).Decode(&result)
Copy after login

This eliminates the need for intermediate conversions or copies.

The above is the detailed content of How to Efficiently Convert a UTF-8 String to []byte for JSON Unmarshalling in Go?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!