Convert JSON to CSV in Golang
Need to load a data file with JSON encoded data and save it to CSV file ? This tutorial will cover just that :
The Golang code below will first read this JSON data file :
data.json
[
{"Name":"Adam","Age":36,"Job":"CEO"},
{"Name":"Eve","Age":34,"Job":"CFO"},
{"Name":"Mike","Age":38,"Job":"COO"}
]
and output to data.csv file
Adam,36,CEO
Eve,34,CFO
Mike,38,COO
json2csv.go
package main
import (
"fmt"
"io/ioutil"
"encoding/json"
"os"
"strconv"
"encoding/csv"
)
type Employee struct {
Name string
Age int
Job string
}
func main() {
// read data from file
jsondatafromfile, err := ioutil.ReadFile("./data.json")
if err != nil {
fmt.Println(err)
}
// Unmarshal JSON data
var jsondata []Employee
err = json.Unmarshal([]byte(jsondatafromfile), &jsondata)
if err != nil {
fmt.Println(err)
}
csvdatafile, err := os.Create("./data.csv")
if err != nil {
fmt.Println(err)
}
defer csvdatafile.Close()
writer := csv.NewWriter(csvdatafile)
for _, worker := range jsondata {
var record []string
record = append(record, worker.Name)
record = append(record, strconv.Itoa(worker.Age))
record = append(record, worker.Job)
writer.Write(record)
}
// remember to flush!
writer.Flush()
}
Hope this simple tutorial can be useful to you.
References :
https://www.socketloop.com/tutorials/golang-convert-type-integer-to-string
https://www.socketloop.com/references/golang-encoding-json-unmarshal-function-example
See also : Golang : Convert CSV data to JSON format and save to file
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+26.4k Golang : Convert file content into array of bytes
+10.9k CodeIgniter : How to check if a session exist in PHP?
+46k Golang : Encode image to base64 example
+20.8k Golang : Sort and reverse sort a slice of strings
+12.4k Golang : Pass database connection to function called from another package and HTTP Handler
+10.2k Golang : Generate 403 Forbidden to protect a page or prevent indexing by search engine
+5.5k Golang : Fix opencv.LoadHaarClassifierCascade The node does not represent a user object error
+16.2k Golang : How to implement two-factor authentication?
+13.9k Golang : Chunk split or divide a string into smaller chunk example
+6.5k Unix/Linux : How to fix CentOS yum duplicate glibc or device-mapper-libs dependency error?
+5.8k Javascript : Get operating system and browser information
+11.4k Golang : Secure file deletion with wipe example