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 use WaitGroup to delay execution of the main function until after all goroutines are complete.
Golang Concurrency Best Practices
Golang write struct to XML file
Pascal triangle in Go Programming Language
How do you create an HTTP client in Go?
How to remove all line breaks from a string in Golang?