JSON Encoding and Decoding
Start with JSON Encoding and Decoding
The encoding/json package converts between Go values and JSON text used in files and web APIs.
What you’ll learn
- Explain the main purpose of json encoding and decoding.
- Read and run the complete Go example in this lesson.
- Apply the concept and recognize common mistakes.
Understand the idea
json.Marshal serializes a Go value into bytes. json.Unmarshal decodes bytes into a pointer to a destination. Exported struct fields are visible to encoding/json; tags such as json:"name" customize JSON field names.
Check encoding errors and decide whether unknown or missing fields matter to your application. Unmarshaling into a struct leaves fields at zero values if absent unless you add separate validation.
Visualize how it works
Follow this diagram before executing the example. Check where a value or decision changes what runs next.
Run a complete Go example
This example is a complete program. Save it as main.go or paste it into the Go Playground.
Go code
package main
import (
"encoding/json"
"fmt"
)
type Student struct {
Name string `json:"name"`
Score int `json:"score"`
}
func main() {
original := Student{Name: "Ava", Score: 92}
data, err := json.Marshal(original)
if err != nil {
panic(err)
}
fmt.Println(string(data))
var parsed Student
if err := json.Unmarshal(data, &parsed); err != nil {
panic(err)
}
fmt.Println(parsed.Name, parsed.Score)
}
Output
{"name":"Ava","score":92}
Ava 92Trace what the program does
Marshal produces compact JSON with lowercase name and score keys. Unmarshal fills an addressable Student value, which prints Ava 92.
Avoid common mistakes
- Unexported struct fields are not serialized by encoding/json.
- Decoding and validating business requirements are separate steps.
Try it yourself
Add a boolean Active field with a json tag; serialize it and verify it decodes correctly.
Tip: Edit the example above, predict the output, and run the modified code to test your reasoning.
Check your understanding
What you should remember
You have practiced JSON Encoding and Decoding in a small, self-contained program. The important habit is to predict what runs, inspect the actual output and distinguish the language rule from the particular example.
Before continuing, make sure you can explain the program to someone who has not seen it, including the line that changes its result.
Reaching the recap and completing the quizzes are separate milestones.