Skip to content

Module 2: JSON Handling (The Packing List)

📚 Module 2: JSON Handling

Course ID: GO-202
Subject: The Packing List

In modern web apps, we don’t send HTML. We send raw data in JSON format.


🏗️ Step 1: Marshaling (The “Packing”)

Turning a Go Struct into a JSON string.

🧩 The Analogy: Packing a Box for Shipping

  • You have a Struct (The physical items).
  • You “Marshal” it (Put it in a cardboard box and tape it up).
  • Now it is a JSON String (A standard box) that any computer can understand.

🏗️ Step 2: Unmarshaling (The “Unpacking”)

Turning a JSON string into a Go Struct.

🧩 The Analogy: Opening the Delivery

  • You receive a JSON Box.
  • You “Unmarshal” it (Open the box and put the items into your specific containers).

🏗️ Step 3: Struct Tags (The “Labels”)

JSON uses lowercase names (e.g., user_name), but Go uses Uppercase for public fields (UserName). We use Struct Tags to link them.

type User struct {
    Name string `json:"user_name"`
    Age  int    `json:"user_age"`
}

🥅 Module 2 Review

  1. Marshal: Turning data into a string.
  2. Unmarshal: Turning a string back into data.
  3. Tags: The map that tells Go which JSON name goes with which Struct field.

:::tip Senior Tip In Go, if you leave a field lowercase (e.g., name), it is Private. The JSON library cannot see it, so it will be empty in your API! Always capitalize your fields. :::