Home > Article > Backend Development > 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
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)
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)
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)
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)
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!