Skip to Content
Skip to content
Go for Beginners: Write Reliable Programs and Small Services
Beginner
Courses
Go for Beginners: Write Reliable Programs and Small Services

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.

Course Home

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 calling json.Unmarshal(data, cfg): Without a pointer (&cfg), Go cannot modify your struct and returns json: 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 run go vet ./..., which flags malformed struct tags.
  • Decoding an untrusted HTTP body without a size cap: Always wrap r.Body with http.MaxBytesReader before calling json.NewDecoder(r.Body).Decode so 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
Was this helpful?
​ 0 ​ 0

Comments

Sign in to comment

No comments yet.