CodeBlanks Logo Icon CodeBlanks

The encoding/json package

Learn the basics of the encoding/json package.

The encoding/json package

encoding/json turns Go values into JSON (Marshal) and JSON into Go values (Unmarshal). Only a struct's exported fields (starting with an upper-case letter) are encoded:

type Urun struct {
    Ad    string
    Fiyat float64
    stok  int  // lower case: not in the JSON
}
b, _ := json.Marshal(Urun{"Kalem", 12.5, 3})
fmt.Println(string(b))  // {"Ad":"Kalem","Fiyat":12.5}

Go and JSON types

Mappings: bool ↔ true/false, numbers ↔ number, string ↔ string, slice/array ↔ array, struct and map[string]T ↔ object, nil ↔ null. []byte becomes base64 text and time.Time RFC 3339 text. Channels, functions and complex numbers can't be encoded; Marshal returns an error.

Practice First Marshal

Define type Urun struct { Ad string; Fiyat float64 }. Encode Urun{"Kalem", 12.5} with json.Marshal; print the error if there is one, otherwise print string(b).

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 Urun struct {
    Ad    string
    Fiyat float64
}

func main() {
    b, err := json.Marshal(Urun{"Kalem", 12.5})
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Println(string(b))
}

Expected output

{"Ad":"Kalem","Fiyat":12.5}

Questions and answers

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

1 Why might a struct field not appear in the JSON output?

  • Because the field is an int
  • Because JSON supports at most 3 fields
  • Because its value is zero (always)
  • Because the field name starts with a lower-case letter Correct answer

Explanation: The json package works through reflection and can't access unexported fields; zero values are written unless omitempty is set.

2 Encode to JSON

Question
b, err := json.____(urun)
Answer
b, err := json.Marshal(urun)

Explanation: json.Marshal converts the value into JSON bytes.

3 Go and JSON

Term Meaning
[]int{1, 2} [1,2]
map[string]int{"a": 1} {"a":1}
nil pointer null
[]byte("hi") "aGk="

All lessons in Intermediate