Go 1.27 reference · Slices, Maps, Iterators and JSON
Go encoding/json Marshal and Unmarshal Function
Convert Go values to JSON and back using struct tags to name fields, omit empty values and skip fields.
Go 1.27
Syntax
func Marshal(v any) ([]byte, error) func Unmarshal(data []byte, v any) error
Parameters
| Parameter | Description |
|---|---|
`json:"name"` |
Field name in JSON. |
`json:",omitempty"` |
Omit zero values. |
`json:"-"` |
Never encode. |
MarshalIndent |
Pretty-printed output. |
Examples
package main
import (
"encoding/json"
"fmt"
)
func main() {
type User struct {
ID int `json:"id"`
Name string `json:"name"`
Email string `json:"email,omitempty"`
Password string `json:"-"`
Tags []string `json:"tags"`
}
b, _ := json.Marshal(User{ID: 1, Name: "Ana", Password: "secret", Tags: []string{"admin"}})
fmt.Println(string(b))
}
Output
{"id":1,"name":"Ana","tags":["admin"]}Run this on your computer — see “Get Started” for setup.
package main
import (
"encoding/json"
"fmt"
)
func main() {
var order struct {
ID int `json:"id"`
Total float64 `json:"total"`
}
err := json.Unmarshal([]byte(`{"id": 42, "total": 19.5, "extra": true}`), &order)
fmt.Println(order.ID, order.Total, err)
var anything map[string]any
json.Unmarshal([]byte(`{"n": 1, "ok": true}`), &anything)
fmt.Printf("%v %T\n", anything["n"], anything["n"])
}
Output
42 19.5 <nil> 1 float64
Run this on your computer — see “Get Started” for setup.
Only exported (capitalised) fields are encoded. Decoding into any turns numbers into float64. For request bodies, use json.NewDecoder with DisallowUnknownFields.
Related
fmt.Printf· Print formatted output using verbs like %v, %+v, %d, %s, %q, %.2f and %T, with width and alignment options.- Go JSON · tutorial