Golang writing struct to JSON file
The json package has a
MarshalIndent()
function which is used to serialized values from a struct and write them to a file in JSON format.
Example
package main
import (
"encoding/json"
"io/ioutil"
)
type Salary struct {
Basic, HRA, TA float64
}
type Employee struct {
FirstName, LastName, Email string
Age int
MonthlySalary []Salary
}
func main() {
data := Employee{
FirstName: "Mark",
LastName: "Jones",
Email: "mark@gmail.com",
Age: 25,
MonthlySalary: []Salary{
Salary{
Basic: 15000.00,
HRA: 5000.00,
TA: 2000.00,
},
Salary{
Basic: 16000.00,
HRA: 5000.00,
TA: 2100.00,
},
Salary{
Basic: 17000.00,
HRA: 5000.00,
TA: 2200.00,
},
},
}
file, _ := json.MarshalIndent(data, "", " ")
_ = ioutil.WriteFile("test.json", file, 0644)
}
Output
{
"FirstName": "Mark",
"LastName": "Jones",
"Email": "mark@gmail.com",
"Age": 25,
"MonthlySalary": [
{
"Basic": 15000,
"HRA": 5000,
"TA": 2000
},
{
"Basic": 16000,
"HRA": 5000,
"TA": 2100
},
{
"Basic": 17000,
"HRA": 5000,
"TA": 2200
}
]
}
Most Helpful This Week
Program in Go language to Calculate Standard Deviation using Math package
GO language program with an example of Hash Table
Golang program for implementation of Selection Sort
Golang program for implementation of Random Maze Generator
Sierpinski Carpet in Go Programming Language
Program to print pyramid using numbers