DEV Community

Ramu Mangalarapu
Ramu Mangalarapu

Posted on

Simple Reading of JSON file in Golang.

Hi,

Today I am going to write simple tutorial about reading file in Golang.

Let's say you want to read json file, you can read using golang os ReadFile.

The json file we are reading is same as in our golang code file.

user.json

{
    "id": "0000001",
    "name": "user",
    "email": "user.email.com",
    "phoneNumber": "+0001"
}
Enter fullscreen mode Exit fullscreen mode

main.go

package main

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

// User is sample object
type User struct {
    ID          string `json:"id"`
    Name        string `json:"name"`
    Email       string `json:"email"`
    PhoneNumber string `json:"phoneNumber"`
}

func main() {
    // provide the file path to read from
    b, err := os.ReadFile("user.json")
    if err != nil {
        log.Fatalf("Failed to read file: %v\n", err)
    }

    // where to store the file contents
    var u User
    json.NewDecoder(bytes.NewBuffer(b)).Decode(&u)

    // printing the file contents or use it for
        // other purposes.
    fmt.Printf("%#v", u)
}

Enter fullscreen mode Exit fullscreen mode

This way can de-serialize to our native Golang types and use them like passing it other functions or doing some computation on it.

Thank you.

Latest comments (0)