Skip to main content
Brave Programmer Logo

BraveProgrammer

BraveProgrammer

HomeProjectsBlogsCoursesLessonsAbout

Site footer

BraveProgrammer

Free coding courses, practical tutorials, and real projects from BraveProgrammer. Learn web development with React, Next.js, and TypeScript.

Navigation

  • Home
  • Projects
  • Blogs
  • Courses

Resources

  • About
  • Lessons

© 2026 BraveProgrammer. All rights reserved.

  1. Courses
  2. /
  3. Go Programming Bootcamp

Lesson 19 of 60 · Go

JSON Marshalling & Unmarshalling

Duration: 20 minutes

JSON in Go

This lesson explains the main concept clearly with beginner-friendly examples and background so you can learn why the code works.

The encoding/json package provides Marshal and Unmarshal.

type User struct {
    ID   int    `json:"id"`
    Name string `json:"name"`
    Age  int    `json:"age,omitempty"`
}

u := User{ID: 1, Name: "Alice"}
bytes, _ := json.Marshal(u)
fmt.Println(string(bytes)) // {"id":1,"name":"Alice"}

Decoding from a request body

func createUser(w http.ResponseWriter, r *http.Request) {
    var u User
    if err := json.NewDecoder(r.Body).Decode(&u); err != nil {
        http.Error(w, err.Error(), http.StatusBadRequest)
        return
    }
    // process u …
    w.WriteHeader(http.StatusCreated)
}

Custom Marshal/Unmarshal

Implement the json.Marshaler and json.Unmarshaler interfaces for special handling.

Info

Struct tags can control field names, omitempty, and more.

Previous: Standard Library: `net/http` – Building a Simple Web ServerNext: Template Rendering with `html/template`