How to Read a JSON File in Golang

To read a JSON file in Go, you can use the “json.Unmarshal()” function from the “encoding/json” package.

JSON is a popular data format that is easy to read and write. It is often used to represent configuration and environment variables because it is a human-readable format that developers can easily understand. JSON files are also easy to parse and can transfer data between different systems.

Example

We have the “data.json” file that contains the following content:

{
  "name"  : "Krunal Lathiya",
  "age"   : 30,
  "email" : "krunal@example.com"
}

Let’s read this JSON file and parse its content.

package main

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

// Define a struct to hold the JSON data
type Student struct {
  Name string `json:"name"`
  Age int `json:"age"`
  Email string `json:"email"`
}

func main() {
  // Open the JSON file
  file, err := os.Open("data.json")
  if err != nil {
    log.Fatalf("Error opening file: %v", err)
  }
  defer file.Close()

  // Read the file content
  content, err := ioutil.ReadAll(file)
  if err != nil {
    log.Fatalf("Error reading file: %v", err)
  }

  // Parse the JSON content
  var student Student
  err = json.Unmarshal(content, &student)
  if err != nil {
    log.Fatalf("Error unmarshalling JSON: %v", err)
  }

  // Use the parsed JSON data
  fmt.Printf("Name: %s\nAge: %d\nEmail: %s\n", 
             student.Name, student.Age, student.Email)
}

Output

Name: Krunal Lathiya
Age: 30
Email: krunal@example.com

In the above code, we defined a Student struct to hold the JSON data.

In the next step, we opened the JSON file using the “os.Open()” function and read its content with the “ioutil.ReadAll()” function.

After that, we parsed the JSON content using the “json.Unmarshal()” function.

Finally, we printed the parsed JSON data to the console.

That’s it for parsing json file in Go.

Leave a Comment