Go Snippet

Struct Tags for JSON Marshalling

Difficulty: Easy

Struct tags tell `encoding/json` how to map Go fields to JSON keys. This snippet covers the canonical tag forms (`json:"name"`, `json:"name,omitempty"`, `json:"-"`), embedded structs, and unmarshalling JSON back into a struct. Use these to produce idiomatic snake_case JSON from Go's PascalCase fields without writing a custom marshaller.

Code Snippets
/

Struct Tags for JSON Marshalling

Struct Tags for JSON Marshalling

Struct tags tell `encoding/json` how to map Go fields to JSON keys. This snippet covers the canonical tag forms (`json:"name"`, `json:"name,omitempty"`, `json:"-"`), embedded structs, and unmarshalling JSON back into a struct. Use these to produce idiomatic snake_case JSON from Go's PascalCase fields without writing a custom marshaller.

Go
Easy
3 snippets
go-structs
go-modules
serialization
rest-api

1,180 views

6

Each tag is a backtick-quoted string with key:"value" pairs. The json key controls how encoding/json sees the field: a plain name renames the JSON key, - excludes the field entirely, and ,omitempty causes the field to be omitted when its value is the type's zero value (empty string, 0, nil pointer). Always tag fields explicitly even when the JSON key matches the Go name; the explicit tag survives renames and signals intent. Note that struct fields must be exported (capitalised) to be marshallable at all.