Skip to content
Justice Tech School

JSON

encoding/json Marshal and Unmarshal convert structs and JSON. Field tags rename keys.

Example
package main

import (
	"encoding/json"
	"fmt"
)

type P struct {
	Name string `json:"name"`
	Age  int    `json:"age"`
}

func main() {
	p := P{Name: "Ada", Age: 30}
	b, _ := json.Marshal(p)
	fmt.Println(string(b))
	var q P
	json.Unmarshal([]byte(`{"name":"Kofi","age":25}`), &q)
	fmt.Println(q.Name, q.Age)
}

Result

{"name":"Ada","age":30}
Kofi 25

Exercise

Struct tag.

`json:""`

Quiz Test

What does Marshal return?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.