Converting UTF-8 Strings to Byte Arrays for JSON Unmarshaling
To unmarshal a JSON string, one must provide an array of bytes ([]byte) as input to the designated function. This article explores methods to convert UTF-8 strings to []byte for this purpose.
Method 1: Direct Type Conversion
The Go language allows direct conversion of strings to []byte using a simple type cast:
s := "some text" b := []byte(s) // b is of type []byte
This method is sanctioned by the language specification, where it states that converting a string to a []byte results in a slice containing individual bytes of the string.
Method 2: Using an io.Reader with json.NewDecoder()
Alternatively, an io.Reader can be utilized with json.NewDecoder(). The provided io.Reader will read from a string without creating a copy, optimizing the process:
s := `{"somekey":"somevalue"}` var result interface{} err := json.NewDecoder(strings.NewReader(s)).Decode(&result)
This method avoids the overhead of copying the string content to a []byte, making it preferable for larger JSON texts.
Note: For small JSON strings, direct type conversion using []byte(s) is still a viable option with negligible performance impact.
Conclusion
This article demonstrates two methods to convert UTF-8 strings to []byte for JSON unmarshaling: a direct type cast and using an io.Reader with json.NewDecoder(). The appropriate method to employ depends on the specific use case and data size.
The above is the detailed content of How to Convert UTF-8 Strings to Byte Arrays for JSON Unmarshaling in Go?. For more information, please follow other related articles on the PHP Chinese website!