Golang ProgramsGolang Programs

Golang read json file into struct

The json package includes Unmarshal() function which supports decoding data from a byte slice into values. The decoded values are generally assigned to struct fields, the field names must be exported and should be in capitalize format.
package main
 
import (
	"encoding/json"
	"fmt"
	"io/ioutil"
)
 
type CatlogNodes struct {
	CatlogNodes []Catlog `json:"catlog_nodes"`
}
 
type Catlog struct {
	Product_id string `json: "product_id"`
	Quantity   int    `json: "quantity"`
}
 
func main() {
	file, _ := ioutil.ReadFile("test.json")
 
	data := CatlogNodes{}
 
	_ = json.Unmarshal([]byte(file), &data)
 
	for i := 0; i < len(data.CatlogNodes); i++ {
		fmt.Println("Product Id: ", data.CatlogNodes[i].Product_id)
		fmt.Println("Quantity: ", data.CatlogNodes[i].Quantity)
	}
 
}

The JSON file test.json is read with the ioutil.ReadFile() function, which returns a byte slice that is decoded into the struct instance using the json.Unmarshal() function. At last, the struct instance member values are printed using for loop to demonstrate that the JSON file was decoded.