json.Marshal and json.Unmarshal
- Version
- 1.27
- Review
- Draft
Summary#
json.Marshal encodes exported struct fields, and json.Unmarshal decodes into a value through a pointer. Struct tags set member names. omitempty skips empty values such as "", while omitzero skips zero values.
Syntax#
data, err := json.Marshal(value)
err = json.Unmarshal(data, &value)
Example#
package main
import (
"encoding/json"
"fmt"
"time"
)
type account struct {
Name string `json:"name"`
Email string `json:"email,omitempty"`
Joined time.Time `json:"joined,omitzero"`
secret string
}
func main() {
data, err := json.Marshal(account{Name: "Lan", secret: "hidden"})
fmt.Println(string(data), err)
var decoded account
input := []byte(`{"NAME":"Minh","email":"minh@example.com","extra":1}`)
err = json.Unmarshal(input, &decoded)
fmt.Println(decoded.Name, decoded.Email, err)
var loose map[string]any
err = json.Unmarshal([]byte(`{"count":3}`), &loose)
fmt.Printf("%T %v\n", loose["count"], err)
}
Expected output#
{"name":"Lan"} <nil>
Minh minh@example.com <nil>
float64 <nil>
Common mistakes#
Unexported fields are skipped without an error. Unknown object keys are ignored by default, and key matching also accepts a different letter case. Numbers decoded into any become float64. omitempty does not omit a zero time.Time.
Version applicability#
Marshal, Unmarshal and omitempty work from Go 1.0. The example uses any from Go 1.18 and needs Go 1.24 or later for the omitzero tag to omit the zero time. Go 1.27 backs encoding/json with the encoding/json/v2 implementation by default. Marshal and unmarshal behavior is preserved, but error message text may differ, so avoid matching on it.
Sources#
- Attribution
- DevLookup contributors
- License
- CC-BY-4.0