0
0
GoHow-ToBeginner · 3 min read

How to Read JSON File in Go: Simple Example and Syntax

To read a JSON file in Go, use os.ReadFile to load the file content, then decode it with json.Unmarshal into a Go struct or map. This lets you easily work with JSON data in your Go programs.
📐

Syntax

Here is the basic syntax to read and parse a JSON file in Go:

  • os.ReadFile: Reads the entire file content into a byte slice.
  • json.Unmarshal: Converts JSON bytes into a Go data structure like a struct or map.
go
data, err := os.ReadFile("filename.json")
if err != nil {
    // handle error
}

var result YourStructOrMap
err = json.Unmarshal(data, &result)
if err != nil {
    // handle error
}
💻

Example

This example reads a JSON file named data.json containing user information and prints the parsed data.

go
package main

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

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

func main() {
    data, err := os.ReadFile("data.json")
    if err != nil {
        fmt.Println("Error reading file:", err)
        return
    }

    var user User
    err = json.Unmarshal(data, &user)
    if err != nil {
        fmt.Println("Error parsing JSON:", err)
        return
    }

    fmt.Printf("User Name: %s, Age: %d\n", user.Name, user.Age)
}
Output
User Name: Alice, Age: 30
⚠️

Common Pitfalls

Common mistakes when reading JSON files in Go include:

  • Not checking errors from os.ReadFile or json.Unmarshal, which can cause crashes or silent failures.
  • Using incorrect struct tags or mismatched field types, causing JSON parsing to fail or fields to be empty.
  • Forgetting to pass a pointer to json.Unmarshal, which prevents data from being filled.
go
package main

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

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

func main() {
    data, err := os.ReadFile("data.json")
    if err != nil {
        fmt.Println("Error reading file:", err)
        return
    }

    var user User
    // Wrong: passing value instead of pointer
    err = json.Unmarshal(data, user) // This will fail silently
    if err != nil {
        fmt.Println("Error parsing JSON:", err)
        return
    }

    fmt.Printf("User Name: %s, Age: %d\n", user.Name, user.Age)
}
Output
Error parsing JSON: json: Unmarshal(non-pointer main.User)
📊

Quick Reference

Tips for reading JSON files in Go:

  • Always check errors after reading files and unmarshaling JSON.
  • Use struct tags to match JSON keys to Go struct fields.
  • Pass a pointer to json.Unmarshal to fill your data structure.
  • Use os.ReadFile for simple file reading in Go 1.16+.

Key Takeaways

Use os.ReadFile to read the JSON file content into bytes.
Decode JSON bytes into Go structs or maps using json.Unmarshal with a pointer.
Always check for errors after reading files and unmarshaling JSON.
Match JSON keys to struct fields using struct tags for correct parsing.
Passing a non-pointer to json.Unmarshal causes an error.