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
What is state in React?
Golang Program to print numbers with diamond pattern
How to create Slice of Struct in Golang?
GO supports the standard arithmetic operators: (Addition, Subtraction, Multiplication, Division,Remainder)
Cannot call non-function <variable> error in Golang
How do you set headers in an HTTP response in Go?