Loading & Parsing a JSON File in Go

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 howencoding/jsonlearns to map JSON keys to Go fields. Without them, you’d be relying on Go’s default capitalisation rules, which works forTitlebut not for lowercase keys. json.Marshalandjson.Unmarshalare 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{}intoJsonlets the function accept either a singlePageor 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.
