Skip to main content
Engineering Notes · March 2015

Loading & Parsing a JSON File in Go

Portrait of Komang Artha Yasa — technology leader, two decades building digital platforms across marketplaces, retail, logistics, fintech, and banking.

A practical example of loading and parsing a JSON file in Go — read from disk, unmarshal into a typed struct, print, and serialize back. Three packages in the standard library do all the work: encoding/json, io/ioutil, and fmt.

The Program

package main

import (
    "encoding/json"
    "fmt"
    "io/ioutil"
    "os"
)

type Page struct {
    ID    int    `json:"id"`
    Title string `json:"title"`
    Url   string `json:"url"`
}

func (p Page) toString() string {
    return toJson(p)
}

func toJson(p interface{}) string {
    bytes, err := json.Marshal(p)
    if err != nil {
        fmt.Println(err.Error())
        os.Exit(1)
    }
    return string(bytes)
}

func main() {
    pages := getPages()
    for _, p := range pages {
        fmt.Println(p.toString())
    }
    fmt.Println(toJson(pages))
}

func getPages() []Page {
    raw, err := ioutil.ReadFile("./pages.json")
    if err != nil {
        fmt.Println(err.Error())
        os.Exit(1)
    }
    var c []Page
    json.Unmarshal(raw, &c)
    return c
}

A few things worth flagging in the code above:

  • The struct tags`json:"id"` and friends — are how encoding/json learns to map JSON keys to Go fields. Without them, you’d be relying on Go’s default capitalisation rules, which works for Title but not for lowercase keys.
  • json.Marshal and json.Unmarshal are the two sides of the same coin — Go struct → JSON bytes, and JSON bytes → Go struct. Both return an error you should actually handle in production; here we’re just exiting for brevity.
  • interface{} in toJson lets the function accept either a single Page or a slice — the standard library inspects the concrete type at runtime.

The Companion JSON

[
  { "id": 1, "title": "About Us", "url": "/about-us" },
  { "id": 2, "title": "Team",     "url": "/team" },
  { "id": 3, "title": "Projects", "url": "/projects" },
  { "id": 4, "title": "Hire Us",  "url": "/hire-us" }
]

Drop this beside main.go as pages.json and run go run main.go.

Thanks to the extensive standard library, which makes it this easy. No extra dependency is needed for round-tripping JSON in Go — and that’s a deliberate design choice that pays off every time you onboard someone new to the language.