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.

GoData Integrity

Code

gosnippet
30 lines
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

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:`.