DEV Community

Ramu Mangalarapu
Ramu Mangalarapu

Posted on

3 1

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.

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (0)

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay