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!