JSON Marshals Byte Slices As Base64
Show that json.Marshal encodes []byte fields as base64 strings and Unmarshal decodes them back to the original bytes without manual encoding steps.
Code
package main
import (
"encoding/json"
"fmt"
)
type Artifact struct {
Name string `json:"name"`
Payload []byte `json:"payload"`
}
func main() {
a := Artifact{Name: "logo", Payload: []byte("bin-data")}
b, err := json.Marshal(a)
if err != nil {
fmt.Println("marshal failed:", err)
return
}
// []byte 字段在 JSON 里是 base64 字符串,不是数字数组
fmt.Println(string(b))
// 解码端自动 base64 还原原始字节,无需手动编解码
var back Artifact
if err := json.Unmarshal(b, &back); err != nil {
fmt.Println("unmarshal failed:", err)
return
}
fmt.Println(back.Payload, string(back.Payload))
}What the code does
JSON Marshals Byte Slices As Base64 reduces to the function main.
Nothing falls through silently — 2 checkpoints test err != nil on the way through.
Applying it
Running the file prints labeled results such as marshal failed:, unmarshal failed: — each operation’s effect is visible in the output.
Statements that set the outcome here
if err != nil {
fmt.Println("marshal failed:", err)
return
}
Interactive Tools for This Topic
Base64 Encoder & DecoderEncode text to Base64 and decode Base64 back to text with UTF-8 support. Handles Unicode characters correctly using TextEncoder and TextDecoder APIs.Base64 Image PreviewPreview a Base64 or data URI image, detect its MIME type from the magic bytes, and see the decoded byte size without uploading anything.Base64url CodecEncode and decode Base64url, the URL- and filename-safe variant that swaps + and / for - and _ and omits padding.Basic & Bearer Auth Header ToolEncode and decode HTTP Authorization Basic and Bearer headers locally with UTF-8 Base64 validation and automatic JWT claim and expiry inspection.
FAQ
- What does JSON Marshals Byte Slices As Base64 print when run?
- Running the file directly is enough — expect labeled output lines such as `marshal failed:`, `unmarshal failed:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.