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

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

Patricia Arquette
Release: 2024-11-05 22:53:02
Original
642 people have browsed it

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.
Copy after login

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>
Copy after login

This will produce the desired output:

{"Content":"Hello"}
Copy after login

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!

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