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
How to Convert Float to String type in Go?
Golang program for implementation of Shell Sort
How do you set headers in an HTTP request with an HTTP client in Go?
GO Program to Check Whether a Number is Even or Odd
How do you create an HTTP client in Go?
How do you handle HTTP server shutdown gracefully in Go?