go
45 lines · 5 steps
Custom JSON marshaling in Go
How implementing MarshalJSON lets you reshape Go structs into exactly the JSON you want.
Explained by
highlit
1package model
2
3import (
4 "encoding/json"
5 "strings"
6 "time"
7)
8
9type Money int64
10
11type Order struct {
12 ID string
13 Customer string
14 Total Money
15 Tags []string
16 CreatedAt time.Time
17 ShippedAt *time.Time
18}
19
20func (m Money) MarshalJSON() ([]byte, error) {
21 dollars := float64(m) / 100
22 return json.Marshal(dollars)
23}
24
25func (o Order) MarshalJSON() ([]byte, error) {
26 type alias struct {
27 ID string `json:"id"`
28 Customer string `json:"customer"`
29 Total Money `json:"total"`
30 Tags string `json:"tags"`
31 CreatedAt string `json:"created_at"`
32 Shipped bool `json:"shipped"`
33 ShippedAt *time.Time `json:"shipped_at,omitempty"`
34 }
35
36 return json.Marshal(alias{
37 ID: o.ID,
38 Customer: o.Customer,
39 Total: o.Total,
40 Tags: strings.Join(o.Tags, ","),
41 CreatedAt: o.CreatedAt.UTC().Format(time.RFC3339),
42 Shipped: o.ShippedAt != nil,
43 ShippedAt: o.ShippedAt,
44 })
45}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Implementing MarshalJSON on a named type customizes its JSON representation everywhere it appears.
- 2A local alias struct lets you reshape fields and tags without recursing into the original type's marshaler.
- 3Derived fields like a boolean flag or formatted timestamp can be computed at serialization time.
Related explainers
go
package handlers import ( "net/http"
Serving embedded static meta files in Gin
embedding
static assets
http caching
Intermediate
6 steps
go
package config import ( "fmt"
A thread-safe config singleton in Go
singleton
concurrency
environment-variables
Intermediate
7 steps
typescript
type CsvColumn<T> = { header: string; value: (row: T) => string | number | boolean | null | undefined; };
Building a type-safe CSV writer in TypeScript
generics
serialization
escaping
Intermediate
7 steps
go
package scheduler import ( "container/heap"
A priority job queue with Go's container/heap
priority-queue
heap
interfaces
Intermediate
9 steps
go
func UploadChunk(c *gin.Context) { uploadID := c.Param("uploadID") if !validUploadID.MatchString(uploadID) { c.JSON(http.StatusBadRequest, gin.H{"error": "invalid upload id"})
Resumable chunked uploads in Gin
file-upload
content-range
streaming
Advanced
9 steps
go
func (h *ArticleHandler) Create(c *gin.Context) { var req struct { Title string `json:"title" binding:"required"` Body string `json:"body" binding:"required"`
Handling a POST request in Gin
request binding
validation
http status codes
Intermediate
7 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/custom-json-marshaling-in-go-explained-go-cec1/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.