Home  >  Article  >  Backend Development  >  How to Convert UTF-8 Strings to []byte for JSON Unmarshalling in Go?

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

Barbara Streisand
Barbara StreisandOriginal
2024-11-01 10:08:02667browse

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>

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>

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!

Statement:
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