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
Golang program for implementation of Linear Search
Program in Go language to Find Largest Element of an Array
How do you handle HTTP responses in Go?
Struct Instantiation Using Pointer Address Operator
Missing return at end of function error in Golang
Golang program for implementation of Pancake Sort