1. Why do we need Marshal/Unmarshal
When you first hear “we'll turn a struct into JSON with one function,” your brain suspects a catch. And it is right: there is a catch, but a friendly one. encoding/json does the routine work for us: walking through struct fields, turning numbers/strings/arrays into JSON format, escaping characters, and so on.
The most important thing is to understand that this is not “automatic telepathy,” but a very concrete pipeline: we either encode a Go value into a sequence of bytes, or decode a sequence of bytes into a Go variable. And this pipeline is very sensitive to types and to which fields we made exportable.
We need this in our training app (a hypothetical CLI todo) so that we can: output tasks as JSON (for example, for integration with other tools), read tasks from JSON, and also describe the external contract in a stable way — which fields are named how, which can be omitted, and which must not be exposed outside.
encoding/json: two operations
At the basic level, in encoding/json we care about two functions:
- json.Marshal(v) — takes a Go value v and returns JSON as []byte.
- json.Unmarshal(data, &v) — takes JSON bytes data and fills the variable v by address.
If you want to remember it in a very human way, Marshal is “pack it up,” and Unmarshal is “unpack it.” And unpack it into an existing box, which is why we need the address of the variable: where to put the result.
This idea of “first encode, then decode” is common to many formats (JSON, XML, gob, etc.): data has to be turned into a portable form and then restored back.
json.Marshal: Go → JSON
Now we will do the simplest thing: take a task struct and turn it into JSON. Pay attention: Marshal returns bytes and an error. An error is not decoration, it is reality: for example, not everything can be serialized correctly (especially when functions, channels, and other joys of life appear in a struct).
package main
import (
"encoding/json"
"fmt"
)
type Task struct {
ID int
Title string
Done bool
}
func main() {
t := Task{ID: 1, Title: "Read about JSON", Done: false}
b, err := json.Marshal(t)
if err != nil {
fmt.Println("marshal:", err)
return
}
fmt.Println(string(b)) // {"ID":1,"Title":"Read about JSON","Done":false}
}
There are two important observations here.
First, the JSON came out with the field names ID, Title, Done — exactly as in Go. This is the default behavior.
Second, the result is one line without line breaks. This is valid JSON, just “compact.” Not very friendly for humans, but ideal for machines.
json.Unmarshal: JSON → Go and why & is needed
Now let's do the reverse operation: take a JSON string and parse it into Task. The most common beginner mistake is to forget &.
Unmarshal works like this: it does not “create a variable for you,” it fills one that already exists. So it needs to know the address where it should write.
package main
import (
"encoding/json"
"fmt"
)
type Task struct {
ID int
Title string
Done bool
}
func main() {
data := []byte(`{"ID":2,"Title":"Write code","Done":true}`)
var t Task
err := json.Unmarshal(data, &t)
if err != nil {
fmt.Println("unmarshal:", err)
return
}
fmt.Printf("%+v\n", t) // {ID:2 Title:Write code Done:true}
}
If you write json.Unmarshal(data, t), the compiler will not always save you with a “nice explanation” — but the meaning of the error is simple: you did not give the function a way to change the variable.
Why only exported fields are encoded
Before we start nicely controlling field names and omitempty, we need to accept one “iron” rule of encoding/json.
Only exported struct fields participate in serialization, that is, those that start with a capital letter. This is not encoding/json being picky, but Go's basic logic: if a field is not exported, external packages (including encoding/json) should not poke at it.
See how the title field simply disappears from JSON, even if it has a value:
package main
import (
"encoding/json"
"fmt"
)
type Task struct {
ID int
title string
}
func main() {
t := Task{ID: 1, title: "Hidden"}
b, _ := json.Marshal(t)
fmt.Println(string(b)) // {"ID":1}
}
A common “naive plan” is to put the tag json:"title" on title string and hope it will start working. Alas: no. Tags control how a field is encoded, but they do not turn an unexported field into an exported one.
2. Tags and the external JSON contract
When a program communicates with the outside world, field names in Go and in JSON almost never match perfectly. In Go, Title is common, while in JSON people often want "title", "created_at", "task_id", and so on. To avoid renaming fields in Go into something awkward, we use tags (struct tags).
A tag is written in backticks after the field type and looks like this: json:"...".
package main
import (
"encoding/json"
"fmt"
)
type Task struct {
ID int `json:"id"`
Title string `json:"title"`
Done bool `json:"done"`
}
func main() {
t := Task{ID: 1, Title: "Tags are useful", Done: false}
b, _ := json.Marshal(t)
fmt.Println(string(b)) // {"id":1,"title":"Tags are useful","done":false}
}
Now the external contract looks more “JSON-like,” while the Go code remains readable.
Mini table about tags
| Tag | What it does when working with JSON |
|---|---|
|
The field is called "title" in JSON |
|
The field is completely ignored (neither encoded nor decoded) |
|
When encoding, the field is omitted if it is “empty” |
(no tag) |
The Go field name is used (Title → "Title") |
And yes, json:"-" is an excellent way to keep things from being exposed that should not be exposed. For example, an internal token, debug information, or a “service flag.”
package main
import (
"encoding/json"
"fmt"
)
type Task struct {
ID int `json:"id"`
Title string `json:"title"`
Secret string `json:"-"`
}
func main() {
t := Task{ID: 1, Title: "Public", Secret: "top-secret"}
b, _ := json.Marshal(t)
fmt.Println(string(b)) // {"id":1,"title":"Public"}
}
omitempty: what it actually does
With omitempty, confusion usually happens, and that's normal: the word sounds like “the field is optional.” But in fact omitempty does something quite different.
omitempty affects encoding only (Marshal): if a field's value is considered “empty,” the field will not appear in the resulting JSON. When decoding (Unmarshal), omitempty changes nothing.
Let's feel this with the Note field. When Note == "", it does not appear in JSON:
package main
import (
"encoding/json"
"fmt"
)
type Task struct {
Title string `json:"title"`
Note string `json:"note,omitempty"`
}
func main() {
t := Task{Title: "Task A"} // Note == ""
b, _ := json.Marshal(t)
fmt.Println(string(b)) // {"title":"Task A"}
}
Now let's fill in Note:
package main
import (
"encoding/json"
"fmt"
)
type Task struct {
Title string `json:"title"`
Note string `json:"note,omitempty"`
}
func main() {
t := Task{Title: "Task A", Note: "Call mom"}
b, _ := json.Marshal(t)
fmt.Println(string(b)) // {"title":"Task A","note":"Call mom"}
}
What counts as “empty” for omitempty
This is worth saying through once calmly, because later you will be catching “why did it disappear” in real projects.
| Field type | Considered empty for omitempty if... |
|---|---|
|
|
|
|
numbers ( , …) |
|
|
(both and empty) |
|
|
|
|
Among the especially surprising items are slices and maps. Both nil and []string{} will be considered empty (both have length 0), and with omitempty the field will disappear.
omitempty and reading with Unmarshal
When you read JSON into a struct, there are two scenarios: the field is present in the JSON, or it is not. If the field is absent, encoding/json simply leaves in the struct whatever was already there — and if the struct was “zero,” the field remains the zero value.
This is very convenient behavior, but it often creates a false sense of “validation.” In reality, this is not a check, but a default.
package main
import (
"encoding/json"
"fmt"
)
type Task struct {
Title string `json:"title"`
Note string `json:"note,omitempty"`
}
func main() {
data := []byte(`{"title":"A"}`) // note is absent
var t Task
_ = json.Unmarshal(data, &t)
fmt.Printf("Title=%q Note=%q\n", t.Title, t.Note) // Title="A" Note=""
}
The important thing to remember here is: the absence of a field in JSON does not mean “everything is okay by business rules.” It only means: “the value was not sent, so it will be zero.” Required field validation is a separate step (but today we deliberately are not covering it).
3. Practice: task list, pretty JSON, and errors
json.MarshalIndent: JSON for humans
Compact JSON is good for transmission over the network and for storage, but when you are debugging an app, you want to see the structure with your eyes. For that, there is json.MarshalIndent.
It does the same thing as Marshal, but adds line breaks and indentation. This is convenient for logs, examples, and diagnostics.
package main
import (
"encoding/json"
"fmt"
)
func main() {
v := map[string]any{
"id": 1,
"title": "Pretty JSON",
"tags": []string{"go", "json"},
}
b, _ := json.MarshalIndent(v, "", " ")
fmt.Println(string(b))
// {
// "id": 1,
// "tags": [
// "go",
// "json"
// ],
// "title": "Pretty JSON"
// }
}
A small remark from the category of “nice little things”: although a normal Go map traversal does not guarantee order, encoding/json sorts keys when encoding a JSON object so that the result is stable. That is why, with identical data, you see identical output, which helps a lot in tests and diffs.
Encode and decode a task list
Now let's do what applications usually do: not one task, but a task list. We will not go into files or build CLI flags yet — what matters for us is to reinforce the Marshal/Unmarshal contract plus tags.
Let's make two small helpers: encodeTasks and decodeTasks.
package main
import "encoding/json"
type Task struct {
ID int `json:"id"`
Title string `json:"title"`
Done bool `json:"done"`
Note string `json:"note,omitempty"`
}
func encodeTasks(tasks []Task) ([]byte, error) {
return json.Marshal(tasks)
}
And now decoding:
package main
import "encoding/json"
func decodeTasks(data []byte) ([]Task, error) {
var tasks []Task
if err := json.Unmarshal(data, &tasks); err != nil {
return nil, err
}
return tasks, nil
}
And let's check this in main to see the “cycle of tasks in nature”:
package main
import (
"fmt"
)
func main() {
tasks := []Task{
{ID: 1, Title: "Learn Marshal", Done: false},
{ID: 2, Title: "Learn Unmarshal", Done: true, Note: "already done"},
}
b, err := encodeTasks(tasks)
if err != nil {
fmt.Println("encode:", err)
return
}
fmt.Println(string(b))
// [{"id":1,"title":"Learn Marshal","done":false},{"id":2,"title":"Learn Unmarshal","done":true,"note":"already done"}]
decoded, err := decodeTasks(b)
if err != nil {
fmt.Println("decode:", err)
return
}
fmt.Printf("%+v\n", decoded)
// [{ID:1 Title:Learn Marshal Done:false Note:} {ID:2 Title:Learn Unmarshal Done:true Note:already done}]
}
Here you may have noticed: the first task's note is absent in JSON (thanks to omitempty), but after Unmarshal the Note field became an empty string. This is normal and expected.
Unmarshal errors: do not lose context
In real life, JSON is often a bit crooked: an extra comma, a missing quote, a wrong field type. So handling error is not “for show,” but basic hygiene.
encoding/json has typed errors, for example *json.SyntaxError, where you can find out the position (offset) of the problem. This is useful at least so that in logs you can understand “where it broke.” Standard material on error handling even gives an example with json.SyntaxError and the Offset field.
Mini example of a syntax error difference:
package main
import (
"encoding/json"
"errors"
"fmt"
)
func main() {
data := []byte(`{"title":}`) // broken JSON
var v map[string]any
err := json.Unmarshal(data, &v)
var syn *json.SyntaxError
if errors.As(err, &syn) {
fmt.Println("bad JSON at byte:", syn.Offset) // bad JSON at byte: ...
return
}
fmt.Println("other error:", err)
}
We are not going deep into beautiful error UX here (that is a separate big topic), but the rule is simple: you must not ignore an Unmarshal error, especially if JSON comes from outside.
4. Typical mistakes when working with Marshal/Unmarshal, tags, and omitempty
Mistake #1: forgetting & in Unmarshal.
This is the most common story: people write json.Unmarshal(data, t) and wonder why nothing gets filled in (or why the compiler complains). Unmarshal must change a variable, so it needs an address: &t. Say to yourself mentally: “where should I write the result?”
Mistake #2: making struct fields unexported and expecting tags to help.
The field title string will not become part of JSON even with the tag json:"title". encoding/json works only with exported fields. If a field should participate in the contract — make it Title string. If a field should not participate — better explicitly exclude it with json:"-" so that it is visible in the code.
Mistake #3: confusing the meaning of omitempty with “optional.”
omitempty does not validate input and does not say that a field “may be omitted.” It only says: “if the value is empty, do not output it during Marshal.” Required fields are checked by separate logic; otherwise you will get silent zero values and very strange bugs.
Mistake #4: being surprised that an empty []T{} behaves like nil with omitempty.
For omitempty, what matters is “empty or not,” not “nil or not nil.” An empty slice and a nil slice both have len == 0, so the field will be omitted. If you need to distinguish these states at the contract level, you will have to design the format consciously (but that is not solved by a single checkbox in a tag).
Mistake #5: ignoring the Marshal/Unmarshal error because “well, JSON is simple.”
JSON really is simple... until {"id":"oops"} arrives instead of a number, or someone adds an extra comma. Always check err. If you want to be “shorter,” remember: short code that crashes in production usually suddenly becomes very long when you start debugging it at night.
GO TO FULL VERSION