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.
Example
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)
}
}
Most Helpful This Week
GO Program to Generate Fibonacci Sequence Up to a Certain Number
Launches 10 Goroutines and each goroutine adding 10 values to a Channel
Cannot use <variable> (type <type>) as type <new-type> error in Golang
How to create an empty Slice in Golang?
Syntax error: unexpected <token> error in Golang
Create and Print Multi Dimensional Slice in Golang