Home >Backend Development >Golang >How to Decode []byte as Strings in Go JSON?

How to Decode []byte as Strings in Go JSON?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-05 22:53:02645browse

How to Decode []byte as Strings in Go JSON?

Decoding []byte as Strings in Go

In Go, when marshaling a []byte slice as a JSON string, the conversion performed by json.Marshal() method encodes the byte slice as a base64-encoded string. As seen in the documentation:

Array and slice values encode as JSON arrays, except that []byte encodes as a base64-encoded string, and a nil slice encodes as the null JSON object.

This conversion is performed to compensate for the lack of a native representation for raw bytes in JSON. The base64 encoding ensures that the byte slice is transported as a valid JSON string.

Overcoming the Encoding

To generate a JSON string with the original content of a []byte field, the data must be converted to a string before marshaling. This can be achieved using the string() function:

<code class="go">    helloStr := "Hello"
    helloSlc := []byte(helloStr)

    obj := Msg{string(helloSlc)}
    json, _ := json.Marshal(obj)
    fmt.Println(string(json))</code>

This will produce the desired output:

{"Content":"Hello"}

This approach ensures that the JSON string contains the original content of the string, rather than its base64-encoded representation.

The above is the detailed content of How to Decode []byte as Strings in Go JSON?. 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