How to Convert UTF-8 Strings to []byte for JSON Unmarshalling in Go?

Barbara Streisand
Release: 2024-11-01 10:08:02
Original
683 people have browsed it

How to Convert UTF-8 Strings to []byte for JSON Unmarshalling in Go?

Unmarshalling UTF-8 Strings to []byte

When working with JSON, the unmarshal function requires an input of type []byte. However, our data could be stored as a UTF-8 string. This article explores how to convert a UTF-8 string to []byte for successful unmarshalling.

Conversion Using []byte(s)

According to the Go specification, a string can be converted to []byte using a simple casting:

<code class="go">s := "some text"
b := []byte(s)</code>
Copy after login

However, this conversion creates a copy of the string's content, which can be inefficient for large strings.

Using io.Reader for Efficient Unmarshal

An alternative approach is to use an io.Reader created from the string:

<code class="go">s := `{&quot;somekey&quot;:&quot;somevalue&quot;}`
reader := strings.NewReader(s)
decoder := json.NewDecoder(reader)
var result interface{}
decoder.Decode(&result)</code>
Copy after login

This method avoids copying the string and is more efficient for large inputs.

Considerations for Different Scenarios

  • For small JSON texts, directly converting to []byte using []byte(s) is acceptable.
  • For large JSON texts or when working with io.Readers, using strings.NewReader and json.NewDecoder provides better efficiency.

In summary, converting UTF-8 strings to []byte for unmarshalling involves either direct casting or using an io.Reader for efficient handling of large inputs. The choice depends on the specific requirements of the application.

The above is the detailed content of How to Convert UTF-8 Strings 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!