In golang read json file is very easy. In this article we will explain how to read a JSON file from the disk and use it in golang.

What is JSON? JSON is a data exchange format used all over the internet. JSON (JavaScript Object Notation) can be used by all high level programming languages.

How to use JSON with golang? The way this works is by first having a json file on your disk. The program then loads the file for parsing, parses it and then you can use it.

golang read json

JSON file

Create a file on your disk (name it: example.json). The golang program below reads the json file and uses the values directly.

The file can contain a one liner. The file content of example.json is:


{"usd":1,"eur":1.2,"gbp": 1.2}

Save the file to example.json. ### golang Example Then create the program below and run it.:


package main

import (
    "encoding/json"
    "fmt"
    "io/ioutil"
)

func main() {
    
    // read file
    data, err := ioutil.ReadFile("./example.json")
    if err != nil {
      fmt.Print(err)
    }

    // define data structure 
    type DayPrice struct {
      USD float32
      EUR float32
      GBP float32
    }

    // json data
    var obj DayPrice

    // unmarshall it
    err = json.Unmarshal(data, &obj)
    if err != nil {
        fmt.Println("error:", err)
    }

    // can access using struct now
    fmt.Printf("USD : %.2f\n", obj.USD);
    fmt.Printf("EUR : %.2f\n", obj.EUR);
    fmt.Printf("GBP : %.2f\n", obj.GBP);

} 

The above program will open the file ‘example.json’ and parse it. You can access the JSON data like any variables.