Understand the contract

encoding/json converts Go values to JSON and decodes JSON into Go values. For structs, ordinary exported fields participate in encoding. Field tags choose JSON names and options. Decoding validates syntax and compatible types, but your application still needs to validate rules such as a nonempty title.

Marshal returns a byte slice and an error; Unmarshal needs a pointer to the destination so it can populate fields. A field named Done can use the tag json:"done" to produce a lowercase key. Unexported fields remain inaccessible to the ordinary encoder even when given a tag.

Work through the example

The example decodes a task, rejects an empty title and encodes the validated value again. The program preserves false as an explicit JSON value. Adding omitempty would omit false, changing the representation. Decide whether absence and false have different meanings for your consumer.

package main

import (
    "encoding/json"
    "fmt"
)

type Task struct {
    Title string `json:"title"`
    Done bool `json:"done"`
}

func main() {
    var task Task
    if err := json.Unmarshal([]byte(`{"title":"Learn Go","done":false}`), &task); err != nil {
        fmt.Println(err); return
    }
    if task.Title == "" { fmt.Println("title is required"); return }
    data, err := json.Marshal(task)
    if err != nil { fmt.Println(err); return }
    fmt.Println(string(data))
}

Watch this boundary

Unmarshal ignores unknown object fields by default. A Decoder can reject them with DisallowUnknownFields, but you must also constrain input size and decide whether trailing data is allowed. Decoding arbitrary numbers into interface values normally produces float64; typed destination fields avoid that default ambiguity.

Practice with a changed input

Try a numeric title, a missing title and an unknown field. Record which cases fail during decoding and which require your explicit application validation.

References & further reading

Need help with your Go backend?

I work with engineering teams on focused Go and Kubernetes platform engagements, with limited consulting availability.

Explore Go consulting services