[Go] Load JSON from a file into a struct

Created on November 30, 2026

Read the file and pass its bytes to json.Unmarshal from encoding/json. The json tags associate keys in the input with struct fields. Save the example data as sample.json.

{
  "users": [
    {
      "name": "Tom",
      "age": 15
    },
    {
      "name": "Bob",
      "age": 30
    }
  ]
}

Run the following program from the directory containing the file.

package main

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

type JsonContent struct {
    Users []User `json:"users"`
}

type User struct {
    Name string `json:"name"`
    Age  int    `json:"age"`
}

func main() {
    f, err := ioutil.ReadFile("./sample.json")
    if err != nil {
        panic(err.Error())
    }

    jsonContent := &JsonContent{}
    err = json.Unmarshal(f, &jsonContent)
    if err != nil {
        panic(err.Error())
    }

    fmt.Printf("%#v", jsonContent)
}
&main.JsonContent{Users:[]main.User{main.User{Name:"Tom", Age:15}, main.User{Name:"Bob", Age:30}}}
Go