golang

Read JSON files with Golang

JSON plays a fundamental role in facilitating the data exchange between applications and devices. It is at the forefront of most API communication from simple to massively complex APIs.

It is therefore no surprise that you will encounter instances where you will read and parse the JSON files into Go code.

In this tutorial, we will learn how to read a JSON file and parse the result into a Go struct which we can use to manipulate the data.

Sample JSON File

Let us start by setting up a basic JSON file which we will use for demonstration purpose. Feel free to use any JSON file for your tasks.

{
    "object_id": 1,
    "object_name": "Rev",
    "object_type": "satellite",
    "object_mass": 766.563,
    "object_radius": 756.1,
    "object_color": "#435e65",
    "object_discovery_date": "10/7/1911",
    "object_distance_from_earth": 43838.71,
    "object_orbit_type": "parabolic",
    "object_temperature": 4209.64
}

In this case, we have a sample data that represents the space object details.

Read the JSON File in Golang

Let us proceed and discuss the various methods and techniques that we can use to read the JSON files.

Method 1: OS

The first method that we can use is taking advantage of the OS package. We can use this package to read the JSON file and then unmarshall it into a Golang struct.

Let us start by defining a struct that mirrors the JSON structure.

package main

type SpaceObj struct {
    ObjectID            int     `json:"object_id"`
    ObjectName          string  `json:"object_name"`
    ObjectType          string  `json:"object_type"`
    ObjectMass          float64 `json:"object_mass"`
    ObjectRadius        float64 `json:"object_radius"`
    ObjectColor         string  `json:"object_color"`
    ObjectDiscoveryDate string  `json:"object_discovery_date"`
    ObjectDistanceEarth float64 `json:"object_distance_from_earth"`
    ObjectOrbitType     string  `json:"object_orbit_type"`
    ObjectTemperature   float64 `json:"object_temperature"`
}

We can then read the file that contains the JSON data using the “ioutil.ReadFile” method as shown in the following example:

file, err := os.Open("space.json")
    if err != nil {
        fmt.Println("Error opening the JSON file:", err)
        return
    }
    defer file.Close()

    data, err := io.ReadAll(file)
    if err != nil {
        fmt.Println("Error reading the JSON file:", err)
        return
    }

Once we read the data from the file, we can umarshall it into a JSON struct as shown in the following example:

var obj SpaceObj

    err = json.Unmarshal(data, &obj)
    if err != nil {
        fmt.Println("Error unmarshaling JSON:", err)
        return
    }

We can then access the struct elements as follows:

fmt.Println("Object Name:", obj.ObjectName)

fmt.Println("Object Mass:", obj.ObjectMass)

fmt.Println("Object Discovery Date:", obj.ObjectDiscoveryDate)

The resulting output is as follows:

Object Name: Rev
Object Mass: 766.563
Object Discovery Date: 10/7/1911

Method 2: Using a Decoder

If you are working with a large file or data streams, it is good to use the JSON decoder which has a better support.

We can read the file and parse the contents into the decoder as follows:

package main

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

type SpaceObj struct {
    ObjectID            int     `json:"object_id"`
    ObjectName          string  `json:"object_name"`
    ObjectType          string  `json:"object_type"`
    ObjectMass          float64 `json:"object_mass"`
    ObjectRadius        float64 `json:"object_radius"`
    ObjectColor         string  `json:"object_color"`
    ObjectDiscoveryDate string  `json:"object_discovery_date"`
    ObjectDistanceEarth float64 `json:"object_distance_from_earth"`
    ObjectOrbitType     string  `json:"object_orbit_type"`
    ObjectTemperature   float64 `json:"object_temperature"`
}

func main() {
    // Open the JSON file for reading
    file, err := os.Open("space.json")
    if err != nil {
        fmt.Println("Error opening the JSON file:", err)
        return
    }
    defer file.Close()

    decoder := json.NewDecoder(file)

    var obj SpaceObj

    if err := decoder.Decode(&obj); err != nil {
        fmt.Println("Error decoding JSON:", err)
        return
    }

    fmt.Println("Object Name:", obj.ObjectName)
    fmt.Println("Object Mass:", obj.ObjectMass)
    fmt.Println("Object Discovery Date:", obj.ObjectDiscoveryDate)
}

This provides a better support for reading large JSON files or streams. However, the result is the same without needing to manually unmarshall it.

Conclusion

In this tutorial, we learned how to read the JSON files into Go structs which we can use to manipulate the data.

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list