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
Sierpinski Carpet in Go Programming Language
How to use WaitGroup to delay execution of the main function until after all goroutines are complete.
Converting Int data type to Float in Go
Go program to find TXT records of a domain
Golang Web Server Example
Golang program for implementation of AVL Trees
What is Slice Data Type in Go?
GO Program to Check Whether a Number is Palindrome or Not
How do you handle HTTP client server alerting in Go?
Program in Go language to Program to Add Two Matrix Using Multi-dimensional Arrays