Read Files and Decode JSON Structs
Read files with os.ReadFile, decode JSON into typed structs with field tags, and catch malformed input early. After this, you can parse configuration or API payloads safely in Go.
Course content
Sign in to save your progress.
-
Before You Write Code
-
Why Go Exists and When to Pick It
-
Run Your First Go Program
-
-
-
Values, Control Flow, and Functions
-
Variables, Types, and Zero Values
-
If, For Loops, and Multiple Return Values
-
-
-
Slices, Maps, and Structs
-
Arrays, Slices, and Why append Matters
-
Maps, Structs, and Pointer Receivers
-
-
-
Errors, Packages, and Testing
-
Handle Errors Without Hiding Them
-
Packages, Exports, and go test
-
-
-
Files, JSON, and a Small HTTP Server
-
Read Files and Decode JSON Structs
-
Build and Test a Small net/http Server
-
-
-
Pointers, Modules, and CLIs
-
Pointers and Memory Basics
-
Managing Dependencies and internal/ Packages
-
Building CLIs With flag, os.Getenv, and Exit Codes
-
-
Reading configuration files and decoding JSON payloads are everyday tasks in backend Go services. Because Go maps JSON keys directly onto typed struct fields, encoding/json catches type mismatches early—but it also hides two silent traps that surprise developers coming from Python's json.loads or JavaScript's JSON.parse.
Skip ahead
If you already read files with os.ReadFile, export struct fields with JSON tags (`omitempty`, `-`), and reject unknown keys with DisallowUnknownFields, move on to "Build and Test a Small net/http Server."
Experiment 1: Reading a config file cleanly with os.ReadFile
For small files like JSON configs (under a few megabytes), os.ReadFile opens, reads every byte, and closes the file handle in one call—and you can check specifically for a missing file with errors.Is(err, os.ErrNotExist):
data, err := os.ReadFile("config.json")
if errors.Is(err, os.ErrNotExist) {
return defaultConfig(), nil
}
if err != nil {
return Config{}, fmt.Errorf("read config.json: %w", err)
}
For huge files (hundreds of megabytes or gigabytes), never load the entire file into RAM with os.ReadFile—stream it with os.Open and json.NewDecoder (covered in Go Intermediate).
Experiment 2: The unexported-field trap (silent zero!)
Watch what happens when you decode JSON into a struct where one field accidentally starts with a lowercase letter:
package main
import (
"encoding/json"
"fmt"
)
type Config struct {
Host string `json:"host"`
port int // BUG: lowercase means unexported — encoding/json cannot see it!
}
func main() {
var cfg Config
_ = json.Unmarshal([]byte(`{"host":"localhost","port":8080}`), &cfg)
fmt.Printf("unexported trap: %+v\n", cfg)
}
unexported trap: {Host:localhost port:0}
Notice the nastiest part: json.Unmarshal returned nil error! Because port is unexported, the encoding/json package literally cannot write to it, so it quietly skips "port": 8080 and leaves cfg.port at its zero value (0). Exporting the field as Port int `json:"port"` fixes it immediately.
Experiment 3: Catching misspelled JSON keys with DisallowUnknownFields
By default, Go ignores extra keys in incoming JSON—which is helpful when reading third-party APIs that add new fields, and dangerous when reading user config files or strict API payloads where a typo like "prto": 8080 would silently fall back to defaults:
dec := json.NewDecoder(bytes.NewReader([]byte(`{"host":"localhost","typo":true}`)))
dec.DisallowUnknownFields()
if err := dec.Decode(&cfg); err != nil {
fmt.Println("strict decode:", err)
}
strict decode: json: unknown field "typo"
Experiment 4: Encoding structs with omitempty and hiding secrets with "-"
Struct tags control both decoding and encoding. Watch how omitempty drops empty optional fields and `json:"-"` guarantees a password hash never accidentally leaks in an API response:
package main
import (
"encoding/json"
"fmt"
)
type User struct {
ID int `json:"id"`
Name string `json:"name"`
Note string `json:"note,omitempty"`
Password string `json:"-"`
}
func main() {
u := User{ID: 7, Name: "Ana", Password: "super-secret"}
b, _ := json.MarshalIndent(u, "", " ")
fmt.Println(string(b))
}
{
"id": 7,
"name": "Ana"
}
Note was empty so omitempty left it out, and Password was excluded completely even though it held "super-secret".
Common mistakes
- Forgetting
&when callingjson.Unmarshal(data, cfg): Without a pointer (&cfg), Go cannot modify your struct and returnsjson: Unmarshal(non-pointer main.Config). - Spaces inside struct tags: Writing
`json: "host"`(with a space after the colon) silently invalidates the tag! Always write`json:"host"`—and rungo vet ./..., which flags malformed struct tags. - Decoding an untrusted HTTP body without a size cap: Always wrap
r.Bodywithhttp.MaxBytesReaderbefore callingjson.NewDecoder(r.Body).Decodeso a single huge upload cannot exhaust memory.
💡 Tip
Remember that omitempty also omits integer 0 and boolean false! If a JSON API needs to send "retries": 0 or "enabled": false explicitly, leave omitempty off—or use a pointer like *bool when distinguishing "unset" from false.
What happens if you skip this step
One lowercase struct field or one stray space in a JSON tag compiles with zero errors and causes your service to start with port 0 or empty credentials—leaving you wondering why your valid JSON file appears to be ignored.
Your JSON payload contains {"host":"db.local","port":5432}, yet after json.Unmarshal(data, &cfg) your struct has cfg.Host == "db.local" and cfg.port == 0 with err == nil. Why?
About
Read files with os.ReadFile, decode JSON into typed structs with field tags, and catch malformed input early. After this, you can parse configuration or API payloads safely in Go.
- Duration
- 5 min
- Last update
- 11/27/2026
Comments
Sign in to commentNo comments yet.