JSON

Marshal structs

The encoding/json package converts Go values to JSON bytes and back. Marshal takes a struct, a slice, a map, or a plain value and returns JSON. Most programs start with Marshal because it shows exactly how Go sees your data. The program below keeps the Go field names, since no tags are set yet.

package main import ( "encoding/json" "fmt" ) type User struct { Name string Age int } func main() { user := User{Name: "Ada", Age: 36} data, err := json.Marshal(user) if err != nil { fmt.Println(err) return } fmt.Println(string(data)) }

go run main.go

{"Name":"Ada","Age":36}

Unmarshal into structs

Unmarshal parses JSON bytes into a value described by a Go type. Pass a pointer so the decoder can fill the struct in place. When the input does not match the target, Unmarshal returns an error instead of stopping the program. Always check that error before you trust the result.

package main import ( "encoding/json" "fmt" ) type User struct { Name string Age int } func main() { raw := []byte(`{"Name":"Ada","Age":36}`) var user User if err := json.Unmarshal(raw, &user); err != nil { fmt.Println(err) return } fmt.Println(user.Name, user.Age) }

Unknown fields in the input are ignored by default, and missing fields keep their zero values. That makes Unmarshal forgiving when a server adds new keys. Strict validation belongs in your own code after decoding.

Field tags

Struct tags rename fields and control what gets emitted. A tag is a small string after the field type, written in backticks. Use omitempty to drop zero values and a dash to skip a field completely. Tags keep secrets like tokens out of logs and responses.

package main import ( "encoding/json" "fmt" ) type User struct { Name string `json:"name"` Age int `json:"age,omitempty"` Token string `json:"-"` } func main() { user := User{Name: "Ada", Token: "secret"} data, err := json.Marshal(user) if err != nil { fmt.Println(err) return } fmt.Println(string(data)) }

{"name":"Ada"}

Age is zero here, so omitempty removes it, and the dash hides Token every time. Lowercase names in tags follow the usual JSON style. The Go field names stay exported with a capital letter so the package can see them.

Encode straight to a writer

Encoder writes JSON straight to a writer such as a file, a network connection, or standard output. There is no need to hold the whole document in memory first. Decoder does the reverse and reads values one by one from a reader. Streaming fits logs, exports, and long feeds of events.

package main import ( "encoding/json" "os" ) type Event struct { Kind string `json:"kind"` Code int `json:"code"` } func main() { events := []Event{{Kind: "start", Code: 1}, {Kind: "stop", Code: 2}} enc := json.NewEncoder(os.Stdout) for _, e := range events { if err := enc.Encode(e); err != nil { panic(err) } } }

{"kind":"start","code":1}
{"kind":"stop","code":2}

Next: Files and IO

Article author: Arthur Isaev