JSON APIs in Go
Start with JSON APIs in Go
In this lesson, explore json apis in go through one small Go program, and connect its output to the language rules behind it.
What you’ll learn
- Explain the main purpose of json apis in go.
- Read and run the complete Go example in this lesson.
- Apply the concept and recognize common mistakes.
Understand the idea
Define structs with JSON tags to control external field names. json.Marshal encodes values, and json.Unmarshal decodes them.
Only exported fields are encoded by the standard JSON package. Keep internal-only fields private or omit them with json:"-".
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 Task struct {
ID int `json:"id"`
Title string `json:"title"`
Secret string `json:"-"`
}
func main() {
task := Task{ID: 5, Title: "Study Go", Secret: "hidden"}
data, err := json.Marshal(task)
if err != nil {
panic(err)
}
fmt.Println(string(data))
}
Output
{"id":5,"title":"Study Go"}Trace what the program does
Marshal encodes the two exported, enabled fields as {"id":5,"title":"Study Go"}. Secret is omitted because its tag is -.
Avoid common mistakes
- Unexported struct fields are ignored by encoding/json.
- Do not directly decode untrusted JSON into privileged database fields without validation.
Try it yourself
Add a completed boolean field with a JSON tag and print the updated representation.
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 APIs in Go 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.