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.

Top comments (0)

We are hiring! Do you want to be our Senior Platform Engineer? Are you capable of chipping in across sysadmin, ops, and site reliability work, while supporting the open source stack that runs DEV and other communities?

This role might just be for you!

Apply now