Go by Example

JSON

Encode and decode JSON structs with field tags and omitempty; use Decoder for stream input and strict field validation.

JSON is a text format for storing or exchanging data. The encoding/json package converts between JSON text and Go values. A struct tag is extra text written beside a field to control its JSON name. By default, Unmarshal ignores fields in the JSON that are not in the Go struct.

Marshal turns exported struct fields into JSON text. A field is exported when its name starts with a capital letter. The omitempty tag skips a field when it has its zero value, the default for its type such as 0, false or an empty string. Unmarshal reads JSON text into a struct.

package main
 
import (
    "encoding/json"
    "fmt"
)
 
type User struct {
    ID    int    `json:"id"`
    Name  string `json:"name"`
    Email string `json:"email,omitempty"`
}
 
func main() {
    data, err := json.Marshal(User{ID: 7, Name: "Ada"})
    if err != nil {
        fmt.Println("encode:", err)
        return
    }
    var user User
    if err := json.Unmarshal(data, &user); err != nil {
        fmt.Println("decode:", err)
        return
    }
    fmt.Println(string(data), user.Name)
}

In production

Use json.Decoder to read a long input stream without loading it all at once. Call DisallowUnknownFields when extra fields should be rejected instead of ignored. Since omitempty skips zero values, use a separate field when a receiver must tell the difference between “not provided” and “provided as zero.”

Enjoyed this? Get more software craft delivered to your inbox.