Marshal goes value → []byte. Unmarshal goes []byte → pointer. Always pass a pointer to Unmarshal.
Struct marshaling with tags
json:"name" renames the field. omitempty skips zero values. A field must be exported (capitalized) to be seen by the encoder.
type User struct {
Name string `json:"name"`
Age int `json:"age,omitempty"`
}
b, _ := json.Marshal(User{Name: "Ada"})
fmt.Println(string(b)) // {"name":"Ada"}
Output
{"name":"Ada"}
MarshalIndent — pretty-printed
b, _ := json.MarshalIndent(User{Name: "Ada", Age: 36}, "", " ")
fmt.Println(string(b))
Output
{
"name": "Ada",
"age": 36
}
Unmarshal into a struct
data := []byte(`{"name":"Ada","age":36}`)
var u User
if err := json.Unmarshal(data, &u); err != nil {
log.Fatal(err)
}
fmt.Println(u)
Unmarshal into a map or any
Use when the shape isn't known. Numbers decode as float64 unless you use json.Decoder.UseNumber().
var v any
json.Unmarshal([]byte(`{"a":1,"b":[2,3]}`), &v)
fmt.Printf("%#v\n", v)