DEV Community

Ramu Mangalarapu
Ramu Mangalarapu

Posted on

Simple Reading of JSON file in Golang.


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.


    "id": "0000001",
    "name": "user",
    "email": "",
    "phoneNumber": "+0001"
Enter fullscreen mode Exit fullscreen mode


package main

import (

// 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

    // 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)