Most APIs today speak JSON. If you build an HTTP service, read a configuration file or call a third-party API, you will convert between JSON and Go data structures all the time. Go's encoding/json package handles this with two pairs of complementary operations: marshalling and unmarshalling for working with byte slices, and encoding and decoding for working with streams.

Marshalling and unmarshalling

Marshalling converts a Go value into JSON bytes. Unmarshalling does the reverse: it parses JSON bytes into a Go value.

json.Marshal takes any Go value and returns a []byte containing the JSON representation:

Go
type User struct {    Name string    Age  int}u := User{Name: "Alice", Age: 30}data, err := json.Marshal(u)if err != nil {    log.Fatal(err)}fmt.Println(string(data)) // {"Name":"Alice","Age":30}

json.Unmarshal takes a JSON byte slice and a pointer to a Go value, and fills the value with the parsed data:

Go
raw := []byte(`{"Name":"Bob","Age":25}`)var u Userif err := json.Unmarshal(raw, &u); err != nil {    log.Fatal(err)}fmt.Println(u.Name) // Bobfmt.Println(u.Age)  // 25

json.Unmarshal requires a pointer so it can modify the value. Passing a non-pointer causes an error at runtime.

When you need human-readable output, for example in logs or config files, json.MarshalIndent adds indentation:

Go
data, err := json.MarshalIndent(u, "", "  ")if err != nil {    log.Fatal(err)}fmt.Println(string(data))// {//   "Name": "Alice",//   "Age": 30// }

Struct tags

The output from json.Marshal in the example above used "Name" and "Age" as JSON keys, the same names as the Go struct fields. In practice, JSON APIs typically use camelCase ("userName") or snake_case ("user_name") instead of Go's exported PascalCase. Struct tags let you pick the JSON name.

A struct tag is a string literal placed after the field type, inside backticks. The encoding/json package reads the json:"..." tag to control how each field is handled:

Go
type User struct {    Name  string `json:"name"`    Age   int    `json:"age"`    Email string `json:"email"`}u := User{Name: "Alice", Age: 30, Email: "alice@example.com"}data, _ := json.Marshal(u)fmt.Println(string(data))// {"name":"Alice","age":30,"email":"alice@example.com"}

The tag renames the field in JSON output without changing the Go field name. Unmarshalling respects the same tag: json.Unmarshal maps "name" in the JSON back to Name in the struct.

Common tag options

Tags can include options after the field name, separated by a comma.

omitempty

The omitempty option omits a field from JSON output when its value is the zero value for its type: 0 for integers, "" for strings, false for booleans, nil for pointers and slices:

Go
type Product struct {    Name     string  `json:"name"`    Price    float64 `json:"price"`    Discount float64 `json:"discount,omitempty"`    Tags     []string `json:"tags,omitempty"`}p := Product{Name: "Book", Price: 29.90}data, _ := json.Marshal(p)fmt.Println(string(data))// {"name":"Book","price":29.9}

Discount and Tags are omitted because they are zero-valued. This keeps JSON payloads concise when optional fields are not set.

The - tag

Using "-" as the tag name tells encoding/json to always ignore that field, both when marshalling and unmarshalling:

Go
type User struct {    Name     string `json:"name"`    Password string `json:"-"`}u := User{Name: "Alice", Password: "secret"}data, _ := json.Marshal(u)fmt.Println(string(data))// {"name":"Alice"}

Password never appears in JSON output and is never populated from JSON input. This is the idiomatic way to exclude sensitive fields from serialization.

Why you should prefer tags

Without tags, encoding/json falls back to using the Go field name as the JSON key. That only works if the JSON API you are talking to happens to use PascalCase, which is uncommon. Relying on the default usually leads to mismatches:

Go
// Without tags — the JSON must use "Name", "CreatedAt", etc.type User struct {    Name      string    CreatedAt time.Time}// With tags — you control the JSON shape, whatever the Go namestype User struct {    Name      string    `json:"name"`    CreatedAt time.Time `json:"created_at"`}

Tags also put the JSON contract in the code where you can see it. A reader does not need to guess what field name the JSON uses, because the tag declares it. When the API renames a field, you change one tag.

Encoding and decoding with streams

json.Marshal and json.Unmarshal work with byte slices, so they read or produce the entire JSON payload in memory at once. For large payloads or when data flows through an io.Reader or io.Writer, this is wasteful. The encoding/json package provides json.Encoder and json.Decoder for stream-based JSON processing.

json.NewEncoder wraps an io.Writer and writes JSON directly into it:

Go
type User struct {    Name string `json:"name"`    Age  int    `json:"age"`}u := User{Name: "Alice", Age: 30}if err := json.NewEncoder(os.Stdout).Encode(u); err != nil {    log.Fatal(err)}// {"name":"Alice","age":30}

This is particularly useful in HTTP handlers, where http.ResponseWriter implements io.Writer:

Go
func handleUser(w http.ResponseWriter, r *http.Request) {    u := User{Name: "Alice", Age: 30}    w.Header().Set("Content-Type", "application/json")    if err := json.NewEncoder(w).Encode(u); err != nil {        log.Println("encode error:", err)    }}

json.NewDecoder wraps an io.Reader and decodes JSON from it. HTTP request bodies implement io.Reader, so json.Decoder is the usual way to parse incoming JSON:

Go
func handleCreate(w http.ResponseWriter, r *http.Request) {    var u User    if err := json.NewDecoder(r.Body).Decode(&u); err != nil {        http.Error(w, "invalid JSON", http.StatusBadRequest)        return    }    fmt.Printf("received: %+v\n", u)}

Decode reads only as much of the stream as needed to populate the target value, leaving the rest of the reader intact. That lets you read multiple values one after another from the same stream, such as a newline-delimited JSON log file:

Go
dec := json.NewDecoder(r)for {    var entry LogEntry    err := dec.Decode(&entry)    if err == io.EOF {        break    }    if err != nil {        log.Fatal(err)    }    process(entry)}

Custom marshalling and unmarshalling

Struct tags cover most JSON mapping needs, but sometimes the default behaviour is not enough. You may need to serialize a type in a format that encoding/json cannot produce on its own: a time.Duration as a human-readable string, a bitmask as an array of names, a value that must change shape depending on a field. The encoding/json package provides two interfaces for this:

Go
type Marshaler interface {    MarshalJSON() ([]byte, error)}type Unmarshaler interface {    UnmarshalJSON([]byte) error}

When json.Marshal encounters a value that implements Marshaler, it calls MarshalJSON and uses the returned bytes as-is. When json.Unmarshal encounters a value that implements Unmarshaler, it calls UnmarshalJSON and passes the raw JSON bytes for the field.

The Marshaler interface

Consider time.Duration. By default, Go represents it as a plain integer (nanoseconds), which is correct but opaque in JSON:

Go
type Config struct {    Timeout time.Duration `json:"timeout"`}c := Config{Timeout: 5 * time.Second}data, _ := json.Marshal(c)fmt.Println(string(data)) // {"timeout":5000000000}

A custom type that wraps time.Duration and implements MarshalJSON can produce a readable string instead:

Go
type Duration struct {    time.Duration}func (d Duration) MarshalJSON() ([]byte, error) {    return json.Marshal(d.String())}

d.String() returns the Go duration string ("5s", "1m30s"). Passing it to json.Marshal produces a quoted JSON string. The updated config type now marshals to a readable value:

Go
type Config struct {    Timeout Duration `json:"timeout"`}c := Config{Timeout: Duration{5 * time.Second}}data, _ := json.Marshal(c)fmt.Println(string(data)) // {"timeout":"5s"}

The Unmarshaler interface

UnmarshalJSON receives the raw JSON bytes for the value (including quotes for strings, brackets for arrays, and so on) and is responsible for parsing them into the receiver. The method must use a pointer receiver so it can modify the value:

Go
func (d *Duration) UnmarshalJSON(data []byte) error {    var s string    if err := json.Unmarshal(data, &s); err != nil {        return err    }    dur, err := time.ParseDuration(s)    if err != nil {        return err    }    d.Duration = dur    return nil}

UnmarshalJSON first parses the raw bytes as a JSON string, then converts it to a time.Duration using time.ParseDuration. The round-trip now works in both directions:

Go
raw := []byte(`{"timeout":"1m30s"}`)var c Configjson.Unmarshal(raw, &c)fmt.Println(c.Timeout.Duration) // 1m30s