JSON
Encode and decode JSON structs with field tags and omitempty; use Decoder for stream input and strict field validation.
The encoding/json package converts Go values to and from JSON. Struct tags control JSON field names, and Unmarshal ignores unknown object fields by default.
Marshal encodes the exported fields. The email field is omitted when empty because its tag includes omitempty. Unmarshal decodes the JSON back 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 for request bodies or other streams, and call DisallowUnknownFields when the input contract should reject extra fields. omitempty omits zero values, so use a pointer or nullable type when clients must distinguish an absent field from an explicit zero. Go 1.27 adds encoding/json/v2 with stricter defaults; the existing encoding/json API remains supported.