CodeBlanks Logo Icon CodeBlanks

Marshal and Unmarshal

Learn to produce JSON with Marshal and parse with Unmarshal.

Unmarshal

json.Unmarshal(data, &target) decodes JSON bytes into a Go value. The target must be a pointer; otherwise the package can't fill it.

var u Urun
err := json.Unmarshal([]byte(`{"ad":"Kalem","fiyat":12.5}`), &u)
if err != nil {
    return err
}
fmt.Println(u.Ad, u.Fiyat)

A type mismatch (e.g. text where a number is expected) returns *json.UnmarshalTypeError; broken JSON returns *json.SyntaxError.

Telling a missing field apart

"adet":0 and not sending the count at all look the same. To tell them apart, use a pointer field:

type Guncelle struct {
    Adet *int `json:"adet"`
}
// {"adet":0}  → Adet != nil, *Adet == 0
// {}          → Adet == nil (not sent)

This distinction matters in PATCH-style APIs.

Practice Decode JSON

Define type Siparis struct { ID int `json:"id"`; Urunler []string `json:"urunler"` }. Decode the text {"id":7,"urunler":["kalem","defter"]} and print ID and the number of products.

Starter code

main.go
package main

import (
    "encoding/json"
    "fmt"
)

func main() {
    // buraya yaz
}

Sample solution

main.go
package main

import (
    "encoding/json"
    "fmt"
)

type Siparis struct {
    ID      int      `json:"id"`
    Urunler []string `json:"urunler"`
}

func main() {
    veri := []byte(`{"id":7,"urunler":["kalem","defter"]}`)
    var s Siparis
    if err := json.Unmarshal(veri, &s); err != nil {
        fmt.Println(err)
        return
    }
    fmt.Println(s.ID, len(s.Urunler))
}

Expected output

7 2

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 After Unmarshal, what happens to a struct field missing from the JSON?

  • It is deleted
  • It keeps its previous value (usually the zero value) Correct answer
  • An error is returned
  • It becomes nil

Explanation: Unmarshal only touches fields present in the JSON; that lets you decode into a struct with defaults and change only the given fields.

2 Pass a pointer

Question
var s Sepet
err := json.Unmarshal(veri, ____)
Answer
var s Sepet
err := json.Unmarshal(veri, &s)

Explanation: Unmarshal needs a pointer to be able to fill the target.

3 Error type

Term Meaning
Bozuk JSON *json.SyntaxError
Wrong type *json.UnmarshalTypeError
Not a pointer *json.InvalidUnmarshalError
Missing field No error, value kept

All lessons in Intermediate