Course › Week 3 · Real data and speed › Day 1 · lesson 15 of 42 · 25 min reading + 60–75 min practice
JSON and struct tags
Typed json_encode and json_decode: struct tags name the fields, and unknown or missing fields are your call.
In PHP, json_decode gives you an array of whatever was in the text. In Go you decode into a struct you defined, so the shape of the JSON is checked and every field has a type.
Go 1.27 added encoding/json/v2, a new version of the standard JSON package with stricter defaults. This course uses it. Older code and most tutorials use encoding/json, which section 10 compares.
Encoding
1. Marshal turns a value into JSON
json.Marshal takes any value and returns its JSON as a []byte and an error.
package main
import (
"encoding/json/v2"
"fmt"
"os"
)
type Booking struct {
ID int
Guest string
Nights int
notes string
}
func main() {
booking := Booking{ID: 1042, Guest: "Astrid", Nights: 3, notes: "late check-in"}
data, err := json.Marshal(booking)
if err != nil {
fmt.Fprintln(os.Stderr, "encoding the booking:", err)
os.Exit(1)
}
fmt.Println(string(data))
}
{"ID":1042,"Guest":"Astrid","Nights":3}The import path is encoding/json/v2, and the package’s name is still json, so calls read json.Marshal. string(data) turns the bytes into a string for printing.
Exported fields become members named exactly like the field. notes is unexported (the packages lesson), so json cannot see it and leaves it out, silently. That is a feature for private data and a classic bug when a field was meant to be in the JSON.
2. Struct tags name the members
A struct tag is a string after a field’s type, in backticks. The json package reads it: the first part is the member’s name, then options.
package main
import (
"encoding/json/v2"
"fmt"
"os"
)
type Booking struct {
ID int `json:"id"`
Guest string `json:"guest_name"`
Nights int `json:"nights"`
CouponCode string `json:"coupon_code,omitzero"`
Tags []string `json:"tags"`
InternalID string `json:"-"`
}
func main() {
booking := Booking{ID: 1042, Guest: "Astrid", Nights: 3, InternalID: "bk_93f2"}
data, err := json.Marshal(booking)
if err != nil {
fmt.Fprintln(os.Stderr, "encoding the booking:", err)
os.Exit(1)
}
fmt.Println(string(data))
}
{"id":1042,"guest_name":"Astrid","nights":3,"tags":[]}Backticks make a raw string in Go: no escapes, so the quotes inside need no backslashes. gofmt lines up the tags in a column.
omitzero leaves the member out when the field is its zero value, here an empty coupon code. json:"-" never writes the field at all. Tags was never set, a nil slice (the slices lesson), and v2 writes it as [], which is what a JavaScript client expects.
Decoding
3. Unmarshal fills a struct
json.Unmarshal(data, &booking) decodes into the value the pointer points to (the pointers lesson).
package main
import (
"encoding/json/v2"
"fmt"
"os"
)
type Booking struct {
ID int `json:"id"`
Guest string `json:"guest_name"`
Nights int `json:"nights"`
}
func main() {
body := []byte(`{"id": 1042, "guest_name": "Astrid", "channel": "airbnb"}`)
var booking Booking
if err := json.Unmarshal(body, &booking); err != nil {
fmt.Fprintln(os.Stderr, "decoding the booking:", err)
os.Exit(1)
}
fmt.Printf("%+v\n", booking)
}
{ID:1042 Guest:Astrid Nights:0}Two things happened quietly. channel is not a field of Booking, so it was ignored. nights was missing, so Nights kept its zero value, 0. Both are the defaults, and both may be wrong for your data; the next two sections deal with them.
4. A wrong type is an error
What the package does not do quietly is put a string into an int:
package main
import (
"encoding/json/v2"
"fmt"
"os"
)
type Booking struct {
ID int `json:"id"`
Nights int `json:"nights"`
}
func main() {
body := []byte(`{"id": 1042, "nights": "three"}`)
var booking Booking
if err := json.Unmarshal(body, &booking); err != nil {
fmt.Fprintln(os.Stderr, "decoding the booking:", err)
os.Exit(1)
}
fmt.Printf("%+v\n", booking)
}
decoding the booking: json: cannot unmarshal JSON string into Go int within "/nights"
exit status 1The error names the JSON type, the Go type, and where in the document it happened: /nights is a JSON Pointer, the path to the member. For a nested value it reads like /rooms/2/beds.
5. Rejecting unknown members
Every function of the package takes options after its arguments. json.RejectUnknownMembers(true) turns an unexpected member into an error, which is what you want for a request body you validate.
package main
import (
"encoding/json/v2"
"fmt"
"os"
)
type Booking struct {
ID int `json:"id"`
Nights int `json:"nights"`
}
func main() {
body := []byte(`{"id": 1042, "nigths": 3}`)
var booking Booking
if err := json.Unmarshal(body, &booking, json.RejectUnknownMembers(true)); err != nil {
fmt.Fprintln(os.Stderr, "decoding the booking:", err)
os.Exit(1)
}
fmt.Printf("%+v\n", booking)
}
decoding the booking: json: cannot unmarshal JSON string into Go main.Booking: unknown object member name "nigths"
exit status 1The typo nigths would have been ignored, and the booking stored with 0 nights. Rejecting unknown members catches it. Keep the default (ignore) for data from an API you do not control, which may add members at any time.
6. Missing is not zero: a pointer field
When “not given” and “zero” must differ, make the field a pointer. A missing member leaves it nil; a member with 0 points to a 0.
package main
import (
"encoding/json/v2"
"fmt"
"os"
)
type BookingUpdate struct {
Nights *int `json:"nights"`
}
func main() {
for _, body := range []string{`{"nights": 0}`, `{}`} {
var update BookingUpdate
if err := json.Unmarshal([]byte(body), &update); err != nil {
fmt.Fprintln(os.Stderr, "decoding the update:", err)
os.Exit(1)
}
if update.Nights == nil {
fmt.Println(body, "-> nights not given: keep the current value")
} else {
fmt.Println(body, "-> set nights to", *update.Nights)
}
}
}
{"nights": 0} -> set nights to 0
{} -> nights not given: keep the current valueIt is the difference between a PATCH that sets a field to 0 and one that does not touch it. In Laravel you would check $request->has('nights'); in Go the type carries the answer.
7. Names are matched exactly
v2 matches member names with the case they are written in. A member called Nights does not fill a field tagged nights:
package main
import (
"encoding/json/v2"
"fmt"
"os"
)
type Booking struct {
Nights int `json:"nights"`
}
func main() {
var booking Booking
if err := json.Unmarshal([]byte(`{"Nights": 3}`), &booking); err != nil {
fmt.Fprintln(os.Stderr, "decoding the booking:", err)
os.Exit(1)
}
fmt.Println("nights:", booking.Nights)
}
nights: 0Exact matching is predictable: the old package also accepted NIGHTS and nIgHtS, and an attacker could send two spellings of the same member. When an API really mixes case, the tag option case:ignore accepts any spelling for that field.
Streams and the old package
8. Read and write streams, and JSON Lines
json.UnmarshalRead(reader, &v) decodes from any io.Reader and json.MarshalWrite(writer, v) encodes to any io.Writer (the interfaces lesson), with no []byte in between.
For JSON Lines, one JSON value per line, the format the build day writes, use an encoder from the companion package encoding/json/jsontext. It writes each value followed by a newline.
package main
import (
"encoding/json/jsontext"
"encoding/json/v2"
"fmt"
"os"
"strings"
)
type Booking struct {
ID int `json:"id"`
Nights int `json:"nights"`
}
func main() {
var bookings []Booking
input := strings.NewReader(`[{"id": 1042, "nights": 3}, {"id": 1043, "nights": 7}]`)
if err := json.UnmarshalRead(input, &bookings); err != nil {
fmt.Fprintln(os.Stderr, "decoding the bookings:", err)
os.Exit(1)
}
encoder := jsontext.NewEncoder(os.Stdout)
for _, b := range bookings {
if err := json.MarshalEncode(encoder, b); err != nil {
fmt.Fprintln(os.Stderr, "writing a booking:", err)
os.Exit(1)
}
}
if err := json.MarshalWrite(os.Stdout, bookings, jsontext.WithIndent(" ")); err != nil {
fmt.Fprintln(os.Stderr, "writing the bookings:", err)
os.Exit(1)
}
fmt.Println()
}
{"id":1042,"nights":3}
{"id":1043,"nights":7}
[
{
"id": 1042,
"nights": 3
},
{
"id": 1043,
"nights": 7
}
]A JSON array decodes into a slice. jsontext.WithIndent(" ") is an option for pretty output, PHP’s JSON_PRETTY_PRINT. MarshalWrite does not end its output with a newline, hence the fmt.Println().
9. Unknown shapes: any
When you cannot know the shape, decode into any (the interfaces lesson). Objects become map[string]any, arrays []any, numbers float64, strings string, booleans bool, and null becomes nil.
package main
import (
"encoding/json/v2"
"fmt"
"os"
)
func main() {
var payload any
if err := json.Unmarshal([]byte(`{"event": "booking.confirmed", "attempt": 2, "tags": ["vip"]}`), &payload); err != nil {
fmt.Fprintln(os.Stderr, "decoding the webhook:", err)
os.Exit(1)
}
fields, ok := payload.(map[string]any)
if !ok {
fmt.Fprintln(os.Stderr, "the webhook is not a JSON object")
os.Exit(1)
}
for _, key := range []string{"event", "attempt", "tags", "missing"} {
fmt.Printf("%-8s %T %v\n", key, fields[key], fields[key])
}
}
event string booking.confirmed
attempt float64 2
tags []interface {} [vip]
missing <nil> <nil>Every use then needs a type assertion, and every number is a float64, even 2. Decode into a struct whenever you can name the fields you need, even if the JSON has a hundred others: unknown members are ignored.
10. encoding/json, the v1 package
Nearly all Go code written before Go 1.27 imports encoding/json. It is still supported, has the same Marshal and Unmarshal, and since 1.27 runs on the v2 code underneath. The behaviour differs where v2 changed the defaults:
encoding/json (v1) | encoding/json/v2 | |
|---|---|---|
| Member names when decoding | case-insensitive | exact, unless the tag says case:ignore |
| A nil slice or map | null | [] or {} |
| The order of a map’s keys | sorted | no fixed order, unless you pass json.Deterministic(true) |
| Invalid UTF-8 and duplicate member names | accepted | errors |
| Unknown members | ignored; Decoder.DisallowUnknownFields to reject | ignored; RejectUnknownMembers(true) to reject |
omitempty on a number | omits 0 | never omits a number: use omitzero |
When you work in an existing codebase, keep the package it uses and know these differences. In new code, use v2.
Coming from PHP
<?php
$data = json_decode($body, true, flags: JSON_THROW_ON_ERROR); // an array of anything
$nights = (int) ($data['nights'] ?? 0); // missing and "three" both become 0
return response()->json([
'id' => $booking->id,
'guest_name' => $booking->guest,
]);
json_decode checks syntax and nothing else; the shape is checked by your code, or by a Form Request, line by line. A Go struct does half of that work in its type: a string where an int belongs is an error, a pointer field tells you what was missing, and RejectUnknownMembers refuses surprises.
In Laravel, an Eloquent model’s $hidden, $casts and API Resources decide what goes out. In Go, the struct tags do: one struct per shape you send, and the compiler knows them all.
PracticeThe package docs, Learn Go with Tests: Pointers & errors, one small program
Skim the package documentation with go doc encoding/json/v2, especially the part on struct tags. Then do Learn Go with Tests’ Pointers & errors if you have not yet: Week 2 prepared every idea in it.
Exercise: a webhook payload
A payment provider sends {"event": "payment.succeeded", "data": {"booking_id": 1042, "amount_cents": 38850, "currency": "EUR"}}. Define two structs, Webhook and Payment, decode the payload into them, and print the booking ID and the amount as euros. Reject unknown members inside data only, and make currency required: if it is missing, print an error and exit with 1.
Show the solution
package main
import (
"encoding/json/jsontext"
"encoding/json/v2"
"errors"
"fmt"
"os"
)
type Payment struct {
BookingID int `json:"booking_id"`
AmountCents int `json:"amount_cents"`
Currency *string `json:"currency"`
}
type Webhook struct {
Event string `json:"event"`
Data jsontext.Value `json:"data"`
}
func decodePayment(body []byte) (Payment, error) {
var hook Webhook
if err := json.Unmarshal(body, &hook); err != nil {
return Payment{}, fmt.Errorf("decoding the webhook: %w", err)
}
var payment Payment
if err := json.Unmarshal(hook.Data, &payment, json.RejectUnknownMembers(true)); err != nil {
return Payment{}, fmt.Errorf("decoding the payment: %w", err)
}
if payment.Currency == nil {
return Payment{}, errors.New("decoding the payment: currency is required")
}
return payment, nil
}
func main() {
body := []byte(`{"event": "payment.succeeded", "data": {"booking_id": 1042, "amount_cents": 38850, "currency": "EUR"}}`)
payment, err := decodePayment(body)
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
fmt.Printf("booking %d paid %d.%02d %s\n", payment.BookingID, payment.AmountCents/100, payment.AmountCents%100, *payment.Currency)
}
booking 1042 paid 388.50 EURjsontext.Value keeps a member as raw JSON, so the outer object can be lenient and the inner one strict, each with its own options. A Data Payment field would have shared the outer call’s options.
Remember
- Decode into a struct with tags, not into
any; only exported fields are encoded or decoded. - A pointer field tells “missing” from “zero”;
RejectUnknownMembers(true)turns a typo into an error. - New code uses
encoding/json/v2; in old code, know that v1 matches names in any case and writes nil slices asnull.
Tomorrow: CSV, one row at a time, with bad rows reported instead of stopping the import.