Golang ProgramsGolang Programs

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.
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:     "[email protected]",
        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)
}

The Salary struct is defined with json fields. The struct values are initialized and then serialize with the json.MarshalIndent() function. The serialized JSON formatted byte slice is received which then written to a file using the ioutil.WriteFile() function.
The output creates a file with each value in JSON format as below:

{
 "FirstName": "Mark",
 "LastName": "Jones",
 "Email": "[email protected]",
 "Age": 25,
 "MonthlySalary": [
  {
   "Basic": 15000,
   "HRA": 5000,
   "TA": 2000
  },
  {
   "Basic": 16000,
   "HRA": 5000,
   "TA": 2100
  },
  {
   "Basic": 17000,
   "HRA": 5000,
   "TA": 2200
  }
 ]
}