read a json file into struct in go

In go, we can read a JSON file and put its contents into a struct using the encoding/json package.

First, we define the struct with corresponding field names and types that matches the JSON file:

main.go
type Data struct {
    Name string `json:"name"`
    Age  int    `json:"age"`
    City string `json:"city"`
}
110 chars
6 lines

Then, we open and read the JSON file into a byte slice:

main.go
file, err := os.Open("data.json")
if err != nil {
    log.Fatal(err)
}
defer file.Close()

byteValue, err := ioutil.ReadAll(file)
if err != nil {
    log.Fatal(err)
}
167 chars
11 lines

Finally, we unmarshal the byte slice into the struct using json.Unmarshal():

main.go
var data Data
err = json.Unmarshal(byteValue, &data)
if err != nil {
    log.Fatal(err)
}

fmt.Println("Name:", data.Name)
fmt.Println("Age:", data.Age)
fmt.Println("City:", data.City)
185 chars
10 lines

Here's the complete code:

main.go
package main

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

type Data struct {
    Name string `json:"name"`
    Age  int    `json:"age"`
    City string `json:"city"`
}

func main() {
    file, err := os.Open("data.json")
    if err != nil {
        log.Fatal(err)
    }
    defer file.Close()

    byteValue, err := ioutil.ReadAll(file)
    if err != nil {
        log.Fatal(err)
    }

    var data Data
    err = json.Unmarshal(byteValue, &data)
    if err != nil {
        log.Fatal(err)
    }

    fmt.Println("Name:", data.Name)
    fmt.Println("Age:", data.Age)
    fmt.Println("City:", data.City)
}
639 chars
39 lines

related categories

gistlibby LogSnag