Sling Academy
Home/Golang/How to read and write JSON files in Go

How to read and write JSON files in Go

Last updated: November 26, 2024

Introduction

JSON (JavaScript Object Notation) is a lightweight data-interchange format that is easy for humans to read and write, and easy for machines to parse and generate. Go, due to its simplicity and strong typing, is a fantastic language for working with JSON data. In this article, we will explore how to read from and write to JSON files in Golang.

Reading JSON Files in Go

To read a JSON file in Go, we typically need to follow these steps:

  1. Use os.Open to open the file.
  2. Read the file contents into a slice of bytes.
  3. Use json.Unmarshal to parse the JSON data into a Go data structure.

Here is a code example demonstrating the process:

package main

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

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

func main() {
  // Open JSON file
  jsonFile, err := os.Open("data.json")
  if err != nil {
    fmt.Println(err)
    return
  }
  defer jsonFile.Close()

  // Read opened file as a byte array
  byteValue, _ := ioutil.ReadAll(jsonFile)

  // Unmarshal JSON data into our User type
  var users []User
  json.Unmarshal(byteValue, &users)

  // Print parsed data
  for i, u := range users {
    fmt.Printf("User %d: %s, %d\n", i+1, u.Name, u.Age)
  }
}

Writing JSON Files in Go

To write a JSON file in Go, you need to:

  1. Convert your Go data structure into JSON using json.Marshal.
  2. Use ioutil.WriteFile or os.Create and os.Write to write to the file.

Here's how you can write content to a JSON file in Go:

package main

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

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

func main() {
  // Define some data structure
  users := []User{
    {Name: "Alice", Age: 30},
    {Name: "Bob", Age: 25},
  }

  // Convert data structure to JSON
  byteValue, err := json.Marshal(users)
  if err != nil {
    fmt.Println(err)
    return
  }

  // Write to JSON file
  err = ioutil.WriteFile("output.json", byteValue, 0644)
  if err != nil {
    fmt.Println(err)
  }
}

Conclusion

Handling JSON files in Go is straightforward, thanks to the standard library's encoding/json package. Whether you're reading data from a JSON document or writing it, the process incorporates basic file operations combined with simple JSON marshaling and unmarshaling techniques. With these methods at your disposal, you can easily integrate JSON handling into your Go applications.

Next Article: How to read and parse XML files in Go

Previous Article: How to write file using Bufio in Go

Series: File I/O and Operating System Interaction

Golang

Related Articles

You May Also Like

  • How to remove HTML tags in a string in Go
  • How to remove special characters in a string in Go
  • How to remove consecutive whitespace in a string in Go
  • How to count words and characters in a string in Go
  • Relative imports in Go: Tutorial & Examples
  • How to run Python code with Go
  • How to generate slug from title in Go
  • How to create an XML sitemap in Go
  • How to redirect in Go (301, 302, etc)
  • Using Go with MongoDB: CRUD example
  • Auto deploy Go apps with CI/ CD and GitHub Actions
  • Fixing Go error: method redeclared with different receiver type
  • Fixing Go error: copy argument must have slice type
  • Fixing Go error: attempted to use nil slice
  • Fixing Go error: assignment to constant variable
  • Fixing Go error: cannot compare X (type Y) with Z (type W)
  • Fixing Go error: method has pointer receiver, not called with pointer
  • Fixing Go error: assignment mismatch: X variables but Y values
  • Fixing Go error: array index must be non-negative integer constant