Skip to main content
Module 5 · Lesson 4 of 524/50 in the course~12 min
Module lessons (4/5)

Field tags and JSON

Lesson preview5 hands-on exercises readyCourse Go · Module 5 — Structs and methods

json:"nome,omitempty", marshalling/unmarshalling with encoding/json, common errors.

What you'll learn in this lesson

  • Annotate struct fields using raw string tags between backticks (` json:"field,omitempty" `).
  • Serialize and deserialize payloads with json.Marshal and json.Unmarshal.
  • Prevent bugs caused by lowercase (unexported) fields silently ignored by encoding/json.

Overview

A struct tag is a raw string literal between backticks placed immediately after the type of a field. The compiler keeps it intact in the type metadata so that standard packages (encoding/json, encoding/xml) or external libraries (yaml, sqlx, validators) can read it via reflection.

A boolean field Active bool with ,omitempty is omitted from the JSON when it is false, because false is the zero value of the type. If you want to distinguish between "absent" and "explicitly false / 0", use a pointer (*bool or *int).

Sections covered in this lesson

  1. 1Main Tag Options json
  2. 2json.Marshal and json.Unmarshal
  3. 3Beware of omitempty on booleans and 0
  4. 4Distinguish absence from zero value with pointers
  5. 5Multi-tag for JSON, databases and numbers as strings
  6. 6Guided practice
Pro Lesson · Module 5 — Structs and methods

Unlock "Field tags and JSON" and the full Course Go curriculum

`json:"nome,omitempty"`, marshalling/unmarshalling with `encoding/json`, common errors.

Unlock all 5 hands-on exercises in this lesson plus every advanced WebAssembly module with automated checks.

  • Instant access to all advanced modules in Course Go plus 17 more courses
  • Hands-on browser exercises with automated test suites and solutions
  • 14-day money-back guarantee processed via Paddle.com

14-day guarantee · Cancel anytimeModule 1, all 18 interactive games, and cheatsheets are always free.