JSON encoding in Go

JSON encoding converts Go values into JSON data that can be sent or stored, while JSON decoding converts JSON data into Go values. The encoding/json package provides Encoder, Decoder, Marshal, and Unmarshal for these operations.

Minimal example

go
type Response struct {
    Message string `json:"message"`
}

func main() {
    data, _ := json.Marshal(Response{Message: "ok"})
    fmt.Println(string(data))
}

Learn this concept

Lesson 1.16 · net/http handlers and middleware

Used in exercises

Exercise 1.18 · RateLimit HTTP middleware that returns 429 Exercise 1.19 · chi server with /healthz and a rate limit Exercise 1.30 · Optional: X-RateLimit response headers Exercise 3.24 · POST /v1/auth/login: rate limit attempts
Prerequisite conceptsGo structsGo errors