LESSON · 1 OF 28

Marshalling a struct to JSON

Marshalling a struct to JSON

JSON is everywhere in DevOps work: API responses, config files, log lines, cloud provider output. Go handles it through the standard library package encoding/json. The first job is turning a Go value into JSON bytes, which is called marshalling.

json.Marshal takes any value and returns its JSON encoding as a byte slice, plus an error:

go
import "encoding/json"

type Server struct {
    Name string
    Port int
}

s := Server{Name: "web1", Port: 8080}
data, err := json.Marshal(s)
if err != nil {
    return err
}
fmt.Println(string(data))
// {"Name":"web1","Port":8080}

The result is a []byte, so wrap it in string(...) to print it. The error is almost always nil for plain structs, but you still check it - that is the Go rhythm.

The shape to memorise: json.Marshal(v) returns ([]byte, error), and string(data) turns those bytes into something you can print.

Spin up a fresh environment and practice live.
go · fresh machine · ready in under a minute